dongwei8440
2017-06-07 13:44
采纳率: 100%
浏览 234
已采纳

OrderBy之后如何HasMany和BelongsTo Relationships

I created a relationship between the "Review, Games and Info" tables, unfortunately, though, the main table is Games, and he orders me all for Games, While I would like to order the ID of "review" table.

Models: Review
    public function games()
    {
        return $this->hasMany('App\Models\Giochi', 'id_gioco', 'id');
    }
Models: Giochi
    public function review()
    {
            return $this->belongsTo('App\Models\Review', 'id', 'id_gioco');
    }
    public function infogiochi()
    {
            return $this->belongsTo('App\Models\InfoGiochi', 'id', 'id_gioco');
    }
Models: InfoGiochi
    public function games()
    {
        return $this->hasMany('App\Models\Giochi', 'id', 'id_gioco');
    }
Controller:
$review = Giochi::with('Review','InfoGiochi')->orderBy('id','DESC')->get();

Here is a screenshot of my json:

enter image description here

How do I order content for review table IDs?

图片转代码服务由CSDN问答提供 功能建议

我在“评论,游戏和信息”表格之间创建了一个关系,不幸的是,主表格是游戏 他命令我全部参加游戏,虽然我想订购“评论”表的ID。

  Models:Review 
 public function games()
 {  
返回$ this-> hasMany('App \ Models \ Giochi','id_gioco','id'); 
} 
模型:Giochi 
公共函数评论()
 {
返回$ this-  > belongsTo('App \ Models \ Review','id','id_gioco'); 
} 
公共函数infogiochi()
 {
返回$ this-> belongsTo('App \ Models \ InfoGiochi  ','id','id_gioco'); 
} 
模型:InfoGiochi 
公共函数游戏()
 {
返回$ this-> hasMany('App \ Models \ Giochi','id',  'id_gioco'); 
} 
控制器:
 $ review = Giochi :: with('Review','InfoGiochi') - > orderBy('id','DESC') - > get(); \  n   
 
 

以下是我的json的截图:

< / p>

如何为审核表ID订购内容?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • dpglo66848 2017-06-07 17:07
    已采纳

    You have 2 options. You use a join and order in the sql statement or you order it after retrieving the results in the collection.

    Using Join

    Giochi::select('giocos.*')
        ->with('Review','InfoGiochi')
        ->leftJoin('reviews', 'reviews.id', '=', 'giocos.id_gioco')
        ->orderBy('reviews.id','DESC')
        ->get();
    

    Sorting Collection

    Giochi::with('Review','InfoGiochi')
        ->get()
        ->sortByDesc(function($giochi) {
            return $giochi->review->id;
        });
    
    点赞 打赏 评论
  • dousi1970 2017-06-07 13:54

    You can try with a raw query or you can use ->orderBy() directly on review function.

    点赞 打赏 评论
  • dotcraq3249 2017-06-07 14:14

    You can modify your relationship query when you fire it:

    Giochi::with([ 
         'Review' => function ($query) { return $query->orderBy('id','DESC'); },
         'InfoGiochi' 
    ])->orderBy('id','DESC');
    
    点赞 打赏 评论

相关推荐 更多相似问题