我有articles
和features
个表以及一个数据透视article_feature
表。功能表包含commenting
,like
,share
等项目。我还有表comments
和likes
。
在我的函数中,我应该获得文章的所有功能,然后从关系中获取所有结果。基本上告诉laravel为我提供所有功能,并为每个功能给我所有的结果。问题是features
表与comments
和likes
等表没有关联。我想知道是否可以使用hasManyThrough,但不知道怎么做,因为可能有很多功能。我在Article
模型中建立了关系:
public function comments()
{
return $this->hasMany('App\Comment');
}
public function features()
{
return $this->belongsToMany('App\Feature');
}
public function likes()
{
return $this->hasMany('App\Like');
}
这是我的功能:
public function latest(){
$result = Article::with('comments.user')->where('publish', 1)->orderBy('created_at', 'desc')->paginate(15);
$user = JWTAuth::parseToken()->authenticate();
foreach($result as $article){
$articles[$article->id] = $article;
$articleFeatures = $article->features()->get()->toArray();
if (count($articleFeatures) != 0) {
$articles[$article->id]['features'] = $articleFeatures;
$articles[$article->id]['likes'] = $article->likes()->get();
$articles[$article->id]['comments'] = $article->comments()->get();
}
return $articles;
}