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

前端 未结 5 1612
慢半拍i
慢半拍i 2020-12-25 15:19

I have a Product model

class Product extends Model
{
    ...

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

            


        
相关标签:
5条回答
  • 2020-12-25 15:30

    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.

    0 讨论(0)
  • 2020-12-25 15:32

    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);
    
    0 讨论(0)
  • 2020-12-25 15:41

    Use Eloquent accessors

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

    Then

    $product->lowest;
    
    0 讨论(0)
  • 2020-12-25 15:47

    change follow code

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

    to

    // add get as prefix and add posfix Attribute and make camel case function
    public function getLowestAttribute()
    {
        return $this->prices->min('price');
    }
    
    0 讨论(0)
  • 2020-12-25 15:50

    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 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;
    
    0 讨论(0)
提交回复
热议问题