不同 table 之间的关联 table 查询
Association table query between different tables
我有用户、帖子和朋友协会 table 将用户联系在一起。
对于单个用户,我想获取属于该用户好友的用户的所有帖子。
//user model
function posts() {
return $this->hasMany('Post');
}
function friends() {
return $this->belongsToMany('User', 'friends', 'friend_id', 'user_id');
}
//post model
function user() {
return $this->belongsTo('User');
}
如果有人能指出我正确的方向,那就太好了
有点棘手和混乱,但应该可行
$friends = $user->friends()->lists('id');
$friendsPosts = Post::whereIn('user_id', $friends);
定义一个 hasManyThrough
关系,例如:
function friendsPosts() {
return $this->hasManyThrough('Post', 'User', 'post_id', 'user_id');
}
我有用户、帖子和朋友协会 table 将用户联系在一起。
对于单个用户,我想获取属于该用户好友的用户的所有帖子。
//user model
function posts() {
return $this->hasMany('Post');
}
function friends() {
return $this->belongsToMany('User', 'friends', 'friend_id', 'user_id');
}
//post model
function user() {
return $this->belongsTo('User');
}
如果有人能指出我正确的方向,那就太好了
有点棘手和混乱,但应该可行
$friends = $user->friends()->lists('id');
$friendsPosts = Post::whereIn('user_id', $friends);
定义一个 hasManyThrough
关系,例如:
function friendsPosts() {
return $this->hasManyThrough('Post', 'User', 'post_id', 'user_id');
}