使用属于属性的关系,外桌和其中()来构建复杂的雄辩查询



在Laravel 5应用中,我有5个表 - 用户,书籍,作者,关注者和Activity_feeds。

用户可以关注作者,一本书可以有几个作者。制作书后,进行了一个Activity_Feeds条目,引用了book_id。

我需要构建一个雄辩的查询,以获取每个用户的activity_feeds集合,以在他们的主页活动feed中迭代。

我的书模型包括

public function authors()
  {
     return $this->belongsToMany('AppAuthor')->withTimestamps();
  }

activity_stream表看起来像这样(示例数据(

id (1)
user_id (3)
type (New Book)
book_id (18)
created_at etc

,我的用户控制器包括

public function feedItems()
  {
    return $this->hasMany('AppActivityFeed');
  }
public function userFollowings()
  {
    return $this->belongsToMany('AppUser', 'followers', 'follower_id', 'subject_id')->withTimestamps();
  }
public function authorFollowings()
  {
     return $this->belongsToMany('AppAuthor', 'followers', 'follower_id', 'author_id')->withTimestamps();
  }

用户模型中包含的当前查询(不起作用(是

public function getactivityFeedsAttribute()
{
   $userFollowings = $this->userFollowings()->pluck('subject_id')->toArray();
   $authorFollowings = $this->authorFollowings()->pluck('author_id')->toArray();
   $userFeeds = ActivityFeed::whereIn('user_id', $userFollowings)
                             ->orwhereIn('book_id', function($query){
                               $query->select('id')
                                ->from(with(new Book)->getTable())
                                ->whereHas->authors()
                                ->whereIn('id', $authorFollowings);
                                })
                              ->get();
  return $userFeeds;
}

$ userFollowings和$授权效果很好。

我不确定我正在使用正确的语法用于数据[book_id]从activity_feeds行中摘下书ID,我真的不确定我是否可以嵌套表格查找或使用$ QUERY这。这似乎也很复杂。我可能会缺少更直截了当的东西吗?

在刀片中,我像这样称呼

@forelse ($user->activityFeeds as $activityFeed)
  <div class="row">
    <div class="col-2">
      {{ $activityFeed->user->firstname }}
    </div>
    <div class="col-2">
      {{ $activityFeed->type }}
    </div>
  </div>
  <hr>
@empty
    No activity yet
@endforelse

如果我只是查询'activityfeed :: where('user_id',$ userFollowings('

,哪个有效

我会在答案中重写查询,因为评论不是很清晰。

public function getactivityFeedsAttribute()
{
    $userFollowings = $this->userFollowings()->pluck('subject_id')->toArray();
    $authorFollowings = $this->authorFollowings()->pluck('author_id')->toArray();
    $books = Book::whereHas('authors', function ($query) use ($authorFollowings) {
        // Have to be explicit about which id we're talking about
        // or else it's gonna throw an error because it's ambiguous
        $query->whereIn('authors.id', $authorFollowings);
    })->pluck('id')->toArray();
    $userFeeds = ActivityFeed::whereIn('user_id', $userFollowings)
    ->orwhereIn('book_id', $books)
    ->get();
    return $userFeeds;
}

最新更新