Laravel 如何在 Eloquent 模型中添加自定义函数?
我有一个产品模型
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;
相关文章