Laravel - 从关系中获取项目

时间:2016-05-12 09:29:11

标签: php laravel eloquent

我有articlesfeatures个表以及一个数据透视article_feature表。功能表包含commentinglikeshare等项目。我还有表commentslikes。 在我的函数中,我应该获得文章的所有功能,然后从关系中获取所有结果。基本上告诉laravel为我提供所有功能,并为每个功能给我所有的结果。问题是features表与commentslikes等表没有关联。我想知道是否可以使用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;
  }

0 个答案:

没有答案