使用belongsToMany关系,外部表和whereIn()构建复杂的口才查询

时间:2019-05-14 15:24:10

标签: laravel-5 eloquent

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

用户可以关注作者,一本书可以有多个作者。 制作书籍时,将创建一个引用该book_id的activity_feeds条目。

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

“我的书”模型包括

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

activity_stream表如下(带有示例数据)

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

并且我的用户控制器包括

public function feedItems()
  {
    return $this->hasMany('App\ActivityFeed');
  }

public function userFollowings()
  {
    return $this->belongsToMany('App\User', 'followers', 'follower_id', 'subject_id')->withTimestamps();
  }

public function authorFollowings()
  {
     return $this->belongsToMany('App\Author', '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和$ authorFollowings工作正常。

我不确定我使用的数据[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 :: whereIn('user_id',$ userFollowings)'

1 个答案:

答案 0 :(得分:0)

我将在答案中重写查询,因为注释不太清晰。

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;
}