我尝试使用Eloquent在Laravel中定义n:m关系。 我有以下给定的表:
用户:
- ID
- foo
物品:
- ID
用户-物品:
- thing_id
- foo
在我的“User”模型中,我定义了以下关系:
public function things() {
return $this->hasMany('App\Thing', 'user_things', 'foo', 'thing_id');
}
在“Things”模型中,它是对应的部分。
public function users() {
return $this->hasMany('App\User', 'user_things', 'thing_id', 'foo');
}
当我在调用控制器时
$user = User::find(1) //works
//$thing = Thing::find(1) works
$things = $user->things();
return $things
我收到了以下信息:
``` 无法将Illuminate\Database\Eloquent\Relations\HasMany类的对象转换为字符串。 ```
我的问题是,我不能在组合表中使用用户ID作为外键。它必须是foo列。
return dd($things)
时会发生什么?$user->things()
返回一个集合实例。尝试使用动态属性,看看是否有效:$things = $user->things;
或者$things = $user->things->first();
- CrackingTheCode