php Laravel 如何在 Eloquent 模型中添加自定义函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37692482/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 01:19:58  来源:igfitidea点击:

Laravel how to add a custom function in an Eloquent model?

phplaravelmodeleloquent

提问by Harrison

I have a Product model

我有一个产品型号

class Product extends Model
{
    ...

    public function prices()
    {
        return $this->hasMany('App\Price');
    }

    ...
}

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 Illuminate\Database\Eloquent\Relations\Relation

And if I use Product::find(1)->lowest();, it will work. Is it possible to get Product::find(1)->lowest;to work?

如果我使用Product::find(1)->lowest();,它将起作用。可以Product::find(1)->lowest;上班吗?

Any help would be appreciated.

任何帮助,将不胜感激。

回答by Rahul M

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 假定您正在尝试检索相关模型。他们称它们为动态属性。您需要的是自定义属性。

Laravel 6 docs: https://laravel.com/docs/6.x/eloquent-mutators

Laravel 6 文档: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;

回答by huuuk

Use Eloquent accessors

使用 Eloquent访问器

public function getLowestAttribute()
{
    return $this->prices->min('price');
}

Then

然后

$product->lowest;

回答by May Weather VN

you can use above methods or use following method to add a function direct into existing model:

您可以使用上述方法或使用以下方法将函数直接添加到现有模型中:

class Company extends Model
{
    protected $table = 'companies';

    // get detail by id
    static function detail($id)
    {
        return self::find($id)->toArray();
    }

    // get list by condition
    static function list($name = '')
    {
        if ( !empty($name) ) return self::where('name', 'LIKE', $name)->get()->toArray();
        else return self::all()->toArray();
    }
}

Or use Illuminate\Support\Facades\DB; inside your function. Hope this help others.

或者使用 Illuminate\Support\Facades\DB; 在你的函数中。希望这对其他人有帮助。

回答by Achraf Khouadja

why you just dont do this? i know , it's not what you asked for specificallyand it migh be a bad practice sometimes. but in your case i guess it's good.

你为什么不这样做?我知道,这不是你特别要求的,有时这可能是一种不好的做法。但就你而言,我想这很好。

$product = Product::with(['prices' => function ($query) {
   $query->min('price');
}])->find($id);