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

新手上路,请多包涵

我有一个产品模型

class Product extends Model
{
    ...

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

    ...
}

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

 Product::find(1)->lowest;

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

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

但我收到一条错误消息:

 Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation

如果我使用 Product::find(1)->lowest(); ,它将起作用。是否有可能让 Product::find(1)->lowest; 工作?

任何帮助,将不胜感激。

原文由 Harrison 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.5k
2 个回答

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

在 Laravel 9 之前

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

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

 public function getLowestAttribute()
{
    //do whatever you want to do
    return 'lowest price';
}

现在您应该可以像这样访问它:

 Product::find(1)->lowest;

编辑:Laravel 9 中的新功能

Laravel 9 提供了一种处理属性的新方法:

文档: https ://laravel.com/docs/9.x/eloquent-mutators#accessors-and-mutators

 // use Illuminate\Database\Eloquent\Casts\Attribute;

public function lowest(): Attribute
{
     return new Attribute(
        get: function( $originalValue ){
         //do whatever you want to do
         //return $modifiedValue;
      });

     /**
      * Or alternatively:-
      *
      * return Attribute::get( function( $originalValue ){
      *    // do whatever you want to do
      *    // return $modifiedValue;
      * });
      */
}

原文由 Rahul M 发布,翻译遵循 CC BY-SA 4.0 许可协议

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

 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();
    }
}

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

原文由 May‘Habit 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题