我有一個如下“Vehicle”類:(為了保持簡單,我刪除了很多方法和可填充物)<?phpnamespace App;use Illuminate\Database\Eloquent\Model;use App\Trip;class Vehicle extends Model{ public $fillable = [ ... ]; protected $appends = [ 'LastTrip' ]; public function trips() { return $this->hasMany(Trip::class); } public function getLastTripAttribute() { return $this->trips->last(); }}問題是,當我從控制器返回此類的實例時。它序列化了“旅行”關系,因此每次旅行都在我的響應中。然而,這只發生在我試圖附加'LastTrip'訪問器。如果我將其更改為以下內容,則問題不會持續存在protected $appends = [ #'LastTrip'];我只是試圖讓它序列化“LastTrip”訪問器。我希望我把我的問題說清楚了,請讓我知道,如果我可以應用任何進一步的信息。感謝您的幫助。
2 回答

斯蒂芬大帝
TA貢獻1827條經驗 獲得超8個贊
發生這種情況是因為您的訪問器執行以下操作:
加載完整行程關系
將行程集合中的最后一個項目設置為last_trip屬性。
將代碼更改為以下內容:
public function getLastTripAttribute()
{
// If the relation is already loaded, avoid doing an extra SQL query
if ($this->relationLoaded('trips')) {
return $this->trips->last();
// Otherwise, get the last trip from an SQL query.
} else {
return $this->trips()->orderByDesc('id')->first();
}
}

青春有我
TA貢獻1784條經驗 獲得超8個贊
編輯:
當您調用時,它會獲取所有行程,然后將最后一個行程分配給LastTrip。但是,如果您在“行程”之后使用括號,則它必須從數據庫中僅獲得1行,請嘗試以下操作:$this->trips->last()
public function getLastTripAttribute(){ return $this->trips()->latest()->first(); }
或
public function getLastTripAttribute(){ return $this->trips()->orderByDesc('id')->first(); }
- 2 回答
- 0 關注
- 117 瀏覽
添加回答
舉報
0/150
提交
取消