【问题标题】:Association table query between different tables不同表之间的关联表查询
【发布时间】:2016-05-29 14:54:45
【问题描述】:

我有用户、帖子和朋友的关联表来将用户联系在一起。

对于单个用户,我想获取属于与该用户成为朋友的用户的所有帖子。

//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');
}

如果有人能指出我正确的方向,那就太好了

【问题讨论】:

    标签: laravel laravel-4 eloquent


    【解决方案1】:

    有点棘手和混乱,但应该可以工作

    $friends = $user->friends()->lists('id');
    $friendsPosts = Post::whereIn('user_id', $friends);
    

    【讨论】:

      【解决方案2】:

      定义hasManyThrough 关系,如:

      function friendsPosts() {
          return $this->hasManyThrough('Post', 'User', 'post_id', 'user_id');
      }
      

      【讨论】:

        猜你喜欢
        • 2015-08-02
        • 2015-04-06
        • 1970-01-01
        • 1970-01-01
        • 2021-11-05
        • 1970-01-01
        • 1970-01-01
        • 2016-03-05
        • 2016-12-11
        相关资源
        最近更新 更多