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

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?

  • 写回答

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;
        });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算