Laravel how to add a custom function in an Eloquen

2019-02-03 08:13发布

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?

Any help would be appreciated.

4条回答
地球回转人心会变
2楼-- · 2019-02-03 08:27

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.

查看更多
我想做一个坏孩纸
3楼-- · 2019-02-03 08:33

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.

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;
查看更多
Summer. ? 凉城
4楼-- · 2019-02-03 08:36

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);
查看更多
甜甜的少女心
5楼-- · 2019-02-03 08:49

Use Eloquent accessors

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

Then

$product->lowest;
查看更多
登录 后发表回答