我有一个产品模型
class Product extends Model
{
...
public function prices()
{
return $this->hasMany('App\Price');
}
...
}
我想添加一个返回最低价格的函数,在 Controller 中我可以使用以下方法获取值:
Product::find(1)->lowest;
我在产品模型中添加了这个:
public function lowest()
{
return $this->prices->min('price');
}
但我收到一条错误消息:
Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation
如果我使用 Product::find(1)->lowest();
,它将起作用。是否有可能让 Product::find(1)->lowest;
工作?
任何帮助将不胜感激。
最佳答案
当您尝试将模型中的函数作为变量访问时,laravel 假定您正在尝试检索相关模型。他们称它们为动态属性。您需要的是自定义属性。
在 Laravel 9 之前
Laravel 6 文档:https://laravel.com/docs/6.x/eloquent-mutators
将以下方法添加到您的模型中:
public function getLowestAttribute()
{
//do whatever you want to do
return 'lowest price';
}
现在您应该可以像这样访问它了:
Product::find(1)->lowest;
编辑:Laravel 9 中的新功能
Laravel 9 提供了一种处理属性的新方法:
文档:https://laravel.com/docs/9.x/eloquent-mutators#accessors-and-mutators
// use Illuminate\Database\Eloquent\Casts\Attribute;
public function lowest(): Attribute
{
return new Attribute(
get: function( $originalValue ){
//do whatever you want to do
//return $modifiedValue;
});
/**
* Or alternatively:-
*
* return Attribute::get( function( $originalValue ){
* // do whatever you want to do
* // return $modifiedValue;
* });
*/
}
关于php - Laravel 如何在 Eloquent 模型中添加自定义函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37692482/