如何从关系laravel向模型添加列



我有一个模型和一个关系,我想将关系中的一列附加到模型中,所以每次调用模型时,关系中的列都应该显示在模型列中。我想按该列对模型进行排序,第二个问题是该列是updated_at,所以如果我可以将其重命名为任何其他列名,那就太好了。这是我的关系和模型代码:我的型号:

public function statusHistory(){
return $this->hasMany(WishStatusHistory::class);
}
public function setUpdatedAtAttribute(){
$this->statusHistory->updated_at;
}

创建一个访问器,如下所示。

public function getNewUpdatedAtAttribute()
{
return $this->statusHistory->updated_at;
}

然后将属性名称添加到模型上的appends属性

protected $appends = ['new_updated_at']; // Modified column name. You can use any. make sure you update the same in method as well

要使用附加列对结果进行排序,请使用sortBy方法。(https://laravel.com/docs/8.x/collections#method-分拣(

$model = Model::all();
$model = $model->sortBy(function($m){
return $m->new_updated_at;
});

也许你可以在你的模型中尝试一下:

public function getUpdatedAtAttribute()
{
return $this->statusHistory->updated_at;
}
// then;
$model->updated_at;

最新更新