Laravel how to add a custom function in an Eloquent model?(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;
这篇关于Laravel 如何在 Eloquent 模型中添加自定义函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Laravel 如何在 Eloquent 模型中添加自定义函数?


- 使用 GD 和 libjpeg 支持编译 PHP 2022-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- 如何使用 Google API 在团队云端硬盘中创建文件夹? 2022-01-01
- 如何在 Symfony2 中正确使用 webSockets 2021-01-01
- 如何从数据库中获取数据以在 laravel 中查看页面? 2022-01-01
- openssl_digest vs hash vs hash_hmac?盐与盐的区别HMAC? 2022-01-01
- PHP foreach() 与数组中的数组? 2022-01-01
- 覆盖 Magento 社区模块控制器的问题 2022-01-01
- Laravel 5:Model.php 中的 MassAssignmentException 2021-01-01
- PHP - if 语句中的倒序 2021-01-01