谢谢你抽出时间来帮助我理解这个问题。
我有一个'Vehicle‘类,如下所示:(为了保持简单,我删除了许多方法和填充物)
<?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();
}
}问题是当我从控制器返回这个类的一个实例时。它序列化了“旅行”关系,这样每次旅行都在我的响应中。
但是,只有当我试图添加'LastTrip‘访问器时,才会发生这种情况。如果我将其更改为以下内容,问题就不会持续存在
protected $appends = [
#'LastTrip'
];我只想让它序列化'LastTrip‘访问器。
我希望我把我的问题说清楚,如果我可以申请任何资料,请告诉我。
谢谢你的帮助。
发布于 2020-02-21 22:01:06
编辑:
当您调用$this->trips->last()时,它会获取所有的行程,然后将最后一个分配给LastTrip。但是,如果在“trips”之后使用括号,则只能从db获得1行,请尝试如下:
public function getLastTripAttribute()
{
return $this->trips()->latest()->first();
}或
public function getLastTripAttribute()
{
return $this->trips()->orderByDesc('id')->first();
}发布于 2020-02-21 22:07:12
之所以会发生这种情况,是因为您的访问器执行以下操作:
relationship
将代码更改为:
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();
}
}https://stackoverflow.com/questions/60346575
复制相似问题