![](/img/trans.png)
[英]How can I sort a Laravel Collection by both string length and alphabetically?
[英]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)
如何基於 Eloquest Series::all() 按劇集 ID 對 desc 進行排序?
[
[...
seasons: [
[...
episodes: [
[id] <---- sort by this
]
]
]
]
我可以根據相同的關系獲得每個系列中每一季的最新一集嗎?
謝謝
問題 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.