亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

拉拉維爾附加訪問器意外地也增加了與響應的關系

拉拉維爾附加訪問器意外地也增加了與響應的關系

PHP
米琪卡哇伊 2022-09-30 16:22:30
我有一個如下“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個贊

發生這種情況是因為您的訪問器執行以下操作:

  1. 加載完整行程關系

  2. 將行程集合中的最后一個項目設置為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();

    }

}


查看完整回答
反對 回復 2022-09-30
?
青春有我

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();
}


查看完整回答
反對 回復 2022-09-30
  • 2 回答
  • 0 關注
  • 117 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號