我已經從我的數據庫belongsToMany
關係沿着加載模型後:修改相關模型的集合執行查詢
$author = Author::with('publications')->first();
/** Returns something like:
{
"id": 3457,
"email": "[email protected]",
"publications": {
"1": {
"id": 240897,
"title": "Food left by other people at a restaurant - is it safe to eat? A comparative review.",
"journal": "Journal of Scrounging and Gleaning",
"year": 2007,
"pivot": {
"author_id": 3457,
"publication_id": 240897
}
},
"2": {
"id": 249196,
"title": "Stop picking at it - you'll leave a scar!",
"journal": "Proceedings of the International Conference on Nagging",
"year": 2008,
"pivot": {
"author_id": 3457,
"publication_id": 249196
}
}
}
}
*/
我再從第三方API取每個publication
一些額外的數據和將它合併到我的收藏集中,效果很好。
不過,我則希望在此基礎上第三方數據的出版物進行排序,所以我用sortByDesc
回調:
$sorted = $author->publications->sortByDesc(function ($publication, $key) {
// Blah blah blah not important how I sort
return $blah;
});
$author->publications = $sorted->values();
按照文檔的sortBy,我需要使用values
如果我想要在排序後對結果重新編號。 $sorted->values()
確實似乎是一個重新鍵入,排序的列表,但即使在將其分配給$author->publications
之後,$author->publications
仍然具有舊密鑰。
更奇怪的是,剛剛運行的sortByDesc
似乎就地排序了列表,即使我沒有將結果返回給$author->publications
。爲什麼我不能將我的重新鍵控收藏重新分配給$author->publications
?我有一種感覺,這與關係與屬性之間的細微差別有關,但我不知道如何解決這個問題。