我有3个模型,User,Subject和Connection,每个模型分别有一个表,用户,主题和连接。 连接表将主题ID与用户ID链接在一起,因此一个用户可以拥有多个不同的主题,反之亦然。
从Connection我发现subject_id == 1的所有实例。
@foreach(... as $value) //Then is the two arrays the $value.
{"id":3,"user_id":"2","subject_id":"1","created_at":"-0001-11-30 00:00:00","updated_at":"-0001-11-30 00:00:00"}
{"id":2,"user_id":"1","subject_id":"1","created_at":"-0001-11-30 00:00:00","updated_at":"-0001-11-30 00:00:00"}
@endforeach
通过foreach循环,我试图从中获取用户。
public function user(){
return $this->belongsTo('User');
}
public function subject(){
return $this->belongsTo('Subject');
}
$ value->主题正常,但$ value->用户只显示任何内容。
我不知道为什么它拒绝向用户显示。 NB。我在不同的模型中有多个具有相同名称的功能,但这不重要吗?
$this->belongsToMany('User')
给了我错误:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'dlh.connection_user' doesn't exist
(SQL:
select users.*,
connection_user.connection_id as pivot_connection_id,
connection_user.user_id as pivot_user_id from users
inner join connection_user on users.id = connection_user.user_id
where connection_user.connection_id = 3
)
我试过这个,但它只返回一个空数组。
return $this->belongsToMany('User', 'connection', 'user_id');
答案 0 :(得分:0)
因为您的用户模型中有多对多关系,所以您应该
class User extends Eloquent {
public function subject()
{
return $this->belongsToMany('Subject','connection_user','user_id', 'subject_id');
}
}
并在您的主题模型中
class Subject extends Eloquent {
public function user()
{
return $this->belongsToMany('User','connection_user','subject_id', 'user_id');
}
}
然后你可以检索记录
$subject= Subject::Find(1);
@foreach ($subject->user as $user)
do something
@endforeach
中的多对多关系