Laravel如何在Eloquent模型中添加自定义函数?
我有一个产品型号Laravel如何在Eloquent模型中添加自定义函数?
class Product extends Model
{
...
public function prices()
{
return $this->hasMany('App\Price');
}
...
}
我想补充这将返回的最低价格的功能,并在控制器我可以用获取的价值:我加入这产品型号
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会假设您尝试检索相关模型。他们称之为动态属性。你需要的是一个自定义属性。
添加下面的方法模型:
public function getLowestAttribute()
{
//do whatever you want to do
return 'lowest price';
}
现在,你应该能够访问它像这样:
Product::find(1)->lowest;
为什么你只是不这样做呢?我知道,这不是你特别要求的,有时这可能是一种不好的做法。但在你的情况下,我想这很好。
$product = Product::find(1)->with(['prices' => function ($query) {
$query->min('price');
}])->get();
他明确要求在模型中的功能。 –
我知道,我只是给了他第二个aproache。 –
使用雄辩accessors
public function getLowestAttribute()
{
return $this->prices->min('price');
}
然后
$product->lowest;
没有OFC因为你调用一个方法,我认为TGAT只会工作一个hasone关系,有什么区别?有还是没有! –