S
S
semki0962019-05-15 13:48:05
Laravel
semki096, 2019-05-15 13:48:05

Why doesn't a one-to-many relationship work?

I can't figure out what the problem is. There is a table with users. And a table with orders.
There is a user_id field in the orders table, it refers to the user id in the user table.
I write a connection in the Order Model. This is how it works (if you specify user_id)

public function userId()
{
    return $this->belongsTo('App\Models\User', 'user_id');
}

But it doesn't work that way - which is strange, because the user_id field exists in the orders table, and it complies with the rules (seemingly).
public function userId()
{
    return $this->belongsTo('App\Models\User');
}

Threat. I looked into the collection, and this is what I saw there
["foreignKey":protected]=>
    string(10) "user_id_id"

That is, for some reason Eloquent added another '_id'. What's my mistake?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
dk-web, 2019-05-15
@semki096

public function user() without ID try

K
Konstantin Tolmachev, 2019-05-15
@dark_tke

Show a one-to-many relationship in the user model, something like this should look like an entry

public function contact()
    {
        return $this->hasMany(Contact::class,'user_id','id');
    }

Where is the first name in the remote table, and at the end is the name in the users table, check if you wrote it correctly

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question