簡體   English   中英

我怎樣才能在 Laravel 中對多重關系進行排序,並找出最新的最深的孩子

[英]How can I both sort multirelationships in laravel and also get out the latest of deepest child

我正在創建一個電影系列數據庫並具有如下模型:

Series
  $with=["seasons"]
  hasMany(App\Seasons)

Season
  $with=["episodes"]
  belongsTo(App\Series)
  hasMany(App\Episode)

Episode
  belongsTo(App\Season)

問題 1

如何基於 Eloquest Series::all() 按劇集 ID 對 desc 進行排序?

[
  [...
    seasons: [
    [...
       episodes: [
          [id]       <---- sort by this
       ]
    ]
  ]
]

問題2

我可以根據相同的關系獲得每個系列中每一季的最新一集嗎?

謝謝

問題 1:

是的。 在構建 Season eloquent 模型時,您需要定義關系,還可以同時應用排序規則等:

public function episodes()
{
    return $this->hasMany(Episode::class)
            ->orderBy('episodes.created_at');
}

問題2:

是的。 您可以像我的第一個答案一樣創建一個新的關系查詢並添加->limit(1)調用。 你可以做的遠不止這些。 請務必查看Laravel 關系文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM