我正在嘗試將 last_messages 訪問器附加到我的聊天模型以附加最后 10 條訊息,但是我收到了這個錯誤:
Method Illuminate\\\\Support\\\\Collection::latest does not exist.
我的訪問器代碼,我使用 $appends 附加
protected $appends = ['has_unread','last_messages'];
public function getLastMessagesAttribute()
{
//return collect($this->messages)->latest('created_at')->first();
return collect($this->messages)->latest('created_at')->take(10)->get();
}
uj5u.com熱心網友回復:
如果這是一個關系,那么您可以通過洗掉方法one-to-many來做到這一點collect
public function getLastMessagesAttribute()
{
return $this->messages()->latest('created_at')->take(10)->get();
}
uj5u.com熱心網友回復:
latest()是一種用于查詢的Eloquent方法,本質上是要求資料庫執行orderBy('created_at', 'desc').
不幸的是,Laravel集合上不存在此方法(因此出現錯誤訊息)。
但是,您可以在您的收藏中使用不同的方法,按照您想要的方式進行這項作業。
嘗試:
return collect($this->messages)->sortBy('created_at');
你可以很狡猾地sortBy使用閉包創建幾乎任何你想要的東西:
$x = $collection->sortBy(function ($product, $key) {
return count($product['colors']);
});
基本方法還采用各種標準 PHP 排序標志來簡化作業。例如:
$collection->sortBy('title', SORT_NATURAL);
查看Laravel 檔案以獲取更多詳細資訊。
uj5u.com熱心網友回復:
我認為您正在匯入錯誤的類。
嘗試匯入這個 -> Illuminate\Database\Eloquent\Collection。在該類中,latest存在一個名為的方法。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/468574.html
