【问题标题】:Fetch news from specific category along with each news writer in laravel从特定类别中获取新闻以及 laravel 中的每个新闻作者
【发布时间】:2020-10-06 00:41:11
【问题描述】:

我在类别模型中有以下功能:

public function news(){
    return $this->belongsToMany(News::class,'news_categories','category_id','news_id');
}

public function writer(){
    return $this->belongsToMany(NewsAuthor::class,'news_authors','news_id','user_id');
}

public static function getNewsByCategory($id, $limit){
    return Category::where('id', $id)->has('news')
      ->with(['news' => function($q) use(&$limit) {
         $q->latest()->limit($limit);
      }])->first();
}

要按类别 id 获取新闻,现在,我还想获取 news_author 表中的新闻作者。

如何使用我的函数getNewsByCategory 获取新闻作者?

【问题讨论】:

    标签: laravel eloquent laravel-relations


    【解决方案1】:

    在新闻模式中添加 $with

    protected $with = ['writers'];
    
    public function writers(){
        return $this->belongsToMany(NewsAuthor::class,'news_authors','news_id','user_id');
    }
    
    // you can get writers for each new
    foreach($category->news as $new) {
      $wirters = $new->writers;
    }
    
    

    【讨论】:

      【解决方案2】:

      为什么不根据laravel docwith([ ... ])中添加writer关系

      public static function getNewsByCategory($id, $limit){
          return Category::where('id', $id)->has('news')
            ->with(['news' => function($q) use(&$limit) {
               $q->latest()->limit($limit);
            }, 'writer'])->first();
      }
      

      查看similar post

      【讨论】:

        猜你喜欢
        • 2019-08-19
        • 1970-01-01
        • 1970-01-01
        • 2011-02-14
        • 2020-12-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-10
        相关资源
        最近更新 更多