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

标签 php laravel model eloquent

我有一个产品模型

class Product extends Model
{
    ...

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

    ...
}

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

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; 工作?

任何帮助将不胜感激。

最佳答案

当您尝试将模型中的函数作为变量访问时,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;
      * });
      */
}

关于php - Laravel 如何在 Eloquent 模型中添加自定义函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37692482/

相关文章:

php - "Has A"或 "Belongs To"关系还是其他什么?

php - 根据最大日期获取每组的最新行

mysql - 使用嵌套子句对查询结果进行排序

php - Laravel 使用 ORDER BY 时获取所有其他字段

c# - 检查隐藏的 bool 值以运行方法

authentication - Yii - 具有自己的 UserIdentity 组件的模块

php - 表 [tablename] 未锁定

php - 允许 PHP 以 root 权限执行 bash 脚本

flutter - 如何从 StreamBuilder 将数据正确保存到我的模型中

asp.net-mvc-3 - MVC 模型在 OnExecuted 操作过滤器中为空……还是设置模型的更优雅的方式?