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 交替优化波束形成和ris反射角使保密速率最大化
  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程