感谢您花时间帮助我理解这个问题。
我有一个“车辆”类,如下所示: (为了保持简单,我删除了很多方法和可填充项)
<?php
namespace 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();
}
}
问题是当我从 Controller 返回此类的实例时。 它将“行程”关系序列化,以便每次行程都在我的响应中。
但这仅在我尝试附加“LastTrip”访问器时才会发生。 如果我将其更改为以下内容,问题就不会持续存在
protected $appends = [
#'LastTrip'
];
我只是想让它序列化“LastTrip”访问器。
我希望我清楚地说明了我的问题,如果我可以应用任何进一步的信息,请告诉我。
感谢您的帮助。
最佳答案
发生这种情况是因为您的访问者执行了以下操作:
- 加载完整的行程关系
- 将 trips 集合中的最后一项设置为 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();
}
}
关于php - Laravel 附加访问器意外地也添加了与响应的关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60346575/