I try do define a n:m relationship in Laravel using Eloquent. I have the following tables given:
users:
- ID
- foo
things
- ID
users_things
- thing_id
- foo
In my User
Model I have defined the following relation
public function things() {
return $this->hasMany('App\Thing', 'user_things', 'foo', 'thing_id');
}
In the Things
Model is the counterpart
public function users() {
return $this->hasMany('App\User', 'user_things', 'thing_id', 'foo');
}
When I call in the Controller
$user = User::find(1) //works
//$thing = Thing::find(1) works
$things = $user->things();
return $things
I get the following message:
Object of class Illuminate\Database\Eloquent\Relations\HasMany could not be converted to string.
My problem is that, I cannot use the User ID
as foreign key in the combination table. It has to be the foo
column.
return dd($things)?
$user->things()` returns an instance of Collection. Use dynamic attribute instead and see if works:$things = $user->things;
or$things = $user->things->first();
– CrackingTheCode