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

前端 未结 5 1631
慢半拍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条回答
  •  梦毁少年i
    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.

提交回复
热议问题