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

Har*_*son 16 php model laravel eloquent

我有一个产品型号

class Product extends Model
{
    ...

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

    ...
}
Run Code Online (Sandbox Code Playgroud)

我想添加一个返回最低价格的函数,在控制器中我可以使用以下方法获取值:

Product::find(1)->lowest;
Run Code Online (Sandbox Code Playgroud)

我在产品型号中添加了这个:

public function lowest()
{
    return $this->prices->min('price');
}
Run Code Online (Sandbox Code Playgroud)

但我得到一个错误说:

Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation
Run Code Online (Sandbox Code Playgroud)

如果我使用Product::find(1)->lowest();它,它会工作.有可能Product::find(1)->lowest;上班吗?

任何帮助,将不胜感激.

Rah*_*l M 32

当您尝试将模型中的函数作为变量访问时,laravel假定您正在尝试检索相关模型.他们称之为动态属性.您需要的是自定义属性.

将以下方法添加到您的模型:

public function getLowestAttribute()
{
    //do whatever you want to do
    return 'lowest price';
}
Run Code Online (Sandbox Code Playgroud)

现在您应该能够像这样访问它:

Product::find(1)->lowest;
Run Code Online (Sandbox Code Playgroud)

  • 我没有意识到您可以使用未定义为基础表中的列的属性来做到这一点;文档没有提到(我可以找到)。 (2认同)
  • @sanders你可以在[Eloquent:Mutators]下找到它(https://laravel.com/docs/5.4/eloquent-mutators#accessors-and-mutators) (2认同)
  • 所以基本上,你必须执行 `get` + 首字母大写的属性名称 + `Attribute()` 才能得到你想要的东西?这很令人困惑,但有效。谢谢。 (2认同)

huu*_*uuk 14

使用Eloquent 访问器

public function getLowestAttribute()
{
    return $this->prices->min('price');
}
Run Code Online (Sandbox Code Playgroud)

然后

$product->lowest;
Run Code Online (Sandbox Code Playgroud)


May*_*bit 8

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

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

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