問題描述
我有一個產品模型
class Product extends Model
{
...
public function prices()
{
return $this->hasMany('AppPrice');
}
...
}
我想添加一個返回最低價格的函數,在控制器中我可以使用以下方法獲取值:
I want to add a function which will return the lowest price, and in controller I can get the value using:
Product::find(1)->lowest;
我在產品模型中添加了這個:
I added this in Product model:
public function lowest()
{
return $this->prices->min('price');
}
但我收到一條錯誤消息:
but I got an error saying:
Relationship method must return an object of type IlluminateDatabaseEloquentRelationsRelation
如果我使用 Product::find(1)->lowest();
,它會起作用.是否可以讓 Product::find(1)->lowest;
工作?
And if I use Product::find(1)->lowest();
, it will work. Is it possible to get Product::find(1)->lowest;
to work?
任何幫助將不勝感激.
推薦答案
當您嘗試將模型中的函數作為變量訪問時,laravel 假定您正在嘗試檢索相關模型.他們稱它們為動態屬性.您需要的是自定義屬性.
When you try to access a function in the model as a variable, laravel assumes you're trying to retrieve a related model. They call them dynamic properties. What you need instead is a custom attribute.
Laravel 6 文檔:https://laravel.com/docs/6.x/雄辯的變異者
Laravel 6 docs: https://laravel.com/docs/6.x/eloquent-mutators
將以下方法添加到您的模型中:
add following method to your model:
public function getLowestAttribute()
{
//do whatever you want to do
return 'lowest price';
}
現在您應該可以像這樣訪問它:
Now you should be able to access it like this:
Product::find(1)->lowest;
這篇關于Laravel 如何在 Eloquent 模型中添加自定義函數?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!