Laravel 如何在 Eloquent 模型中添加自定义函数? [英] Laravel how to add a custom function in an Eloquent model?

查看:28
本文介绍了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 模型中添加自定义函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆