且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Laravel雄辩加入与内部加入?

更新时间:2023-09-11 23:03:10

我确定还有其他方法可以实现此目的,但是一种解决方案是通过查询生成器使用 join .

I'm sure there are other ways to accomplish this, but one solution would be to use join through the Query Builder.

如果您的表设置如下:

users
    id
    ...

friends
    id
    user_id
    friend_id
    ...

votes, comments and status_updates (3 tables)
    id
    user_id
    ....

在您的用户模型中:

class User extends Eloquent {
    public function friends()
    {
        return $this->hasMany('Friend');
    }
}

在您的朋友模型中:

class Friend extends Eloquent {
    public function user()
    {
        return $this->belongsTo('User');
    }
}

然后,要收集ID为1的用户朋友的所有票,可以运行以下查询:

Then, to gather all the votes for the friends of the user with the id of 1, you could run this query:

$user = User::find(1);
$friends_votes = $user->friends()
    ->with('user') // bring along details of the friend
    ->join('votes', 'votes.user_id', '=', 'friends.friend_id')
    ->get(['votes.*']); // exclude extra details from friends table

comments status_updates 表运行相同的 join .如果希望将投票,评论和status_updates放在一个按时间顺序排列的列表中,则可以将结果三个集合合并为一个,然后对合并的集合进行排序.

Run the same join for the comments and status_updates tables. If you would like votes, comments, and status_updates to be in one chronological list, you can merge the resulting three collections into one and then sort the merged collection.

修改

要在一个查询中获得投票,评论和状态更新,可以构建每个查询,然后合并结果.不幸的是,如果我们使用雄辩的 hasMany 关系(

To get votes, comments, and status updates in one query, you could build up each query and then union the results. Unfortunately, this doesn't seem to work if we use the Eloquent hasMany relationship (see comments for this question for a discussion of that problem) so we have to modify to queries to use where instead:

$friends_votes = 
    DB::table('friends')->where('friends.user_id','1')
    ->join('votes', 'votes.user_id', '=', 'friends.friend_id');

$friends_comments = 
    DB::table('friends')->where('friends.user_id','1')
    ->join('comments', 'comments.user_id', '=', 'friends.friend_id');

$friends_status_updates = 
    DB::table('status_updates')->where('status_updates.user_id','1')
    ->join('friends', 'status_updates.user_id', '=', 'friends.friend_id');

$friends_events = 
    $friends_votes
    ->union($friends_comments)
    ->union($friends_status_updates)
    ->get();

但是,在这一点上,我们的查询有点毛茸茸,因此与和一个额外的表(如下面的DefiniteIntegral建议)建立多态关系可能是一个更好的主意.

At this point, though, our query is getting a bit hairy, so a polymorphic relationship with and an extra table (like DefiniteIntegral suggests below) might be a better idea.