在Laravel5应用程序中,我有5个表--用户、书籍、作者、追随者和activity_feeds。
用户可以关注作者,一本书可以有多个作者。当创建一本书时,将创建一个引用book_id的activity_feeds条目。
我需要构建一个雄辩的查询来获得每个用户的activity_feeds集合,以便在他们的主页活动提要中迭代。
我的图书模型包括
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运行得很好。
我不确定我是否使用了正确的databook_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)‘
发布于 2019-05-16 01:44:46
我将在答案中重写查询,因为注释不是很清晰。
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;
}
https://stackoverflow.com/questions/56133881
复制相似问题