55

如果我尝试声明一个属性,如下所示:

public $quantity = 9;

...它不起作用,因为它不被视为“属性”,而仅仅是模型类的属性。不仅如此,我还阻止访问实际真实存在的“数量”属性。

那我该怎么办?

4

5 回答 5

91

对此的更新...

@j-bruni 提交了一个提案,Laravel 4.0.x 现在支持使用以下内容:

protected $attributes = array(
  'subject' => 'A Post'
);

当您构建时,它将自动将您的属性设置subject为。A Post您不需要使用他在回答中提到的自定义构造函数。

但是,如果您最终使用了像他一样的构造函数(我需要这样做才能使用Carbon::now()),请注意这$this->setRawAttributes()将覆盖您使用$attributes上面的数组设置的任何内容。例如:

protected $attributes = array(
  'subject' => 'A Post'
);

public function __construct(array $attributes = array())
{
    $this->setRawAttributes(array(
      'end_date' => Carbon::now()->addDays(10)
    ), true);
    parent::__construct($attributes);
}

// Values after calling `new ModelName`

$model->subject; // null
$model->end_date; // Carbon date object

// To fix, be sure to `array_merge` previous values
public function __construct(array $attributes = array())
{
    $this->setRawAttributes(array_merge($this->attributes, array(
      'end_date' => Carbon::now()->addDays(10)
    )), true);
    parent::__construct($attributes);
}

有关更多信息,请参阅Github 线程

于 2013-12-16T21:33:17.203 回答
56

这就是我现在正在做的事情:

protected $defaults = array(
   'quantity' => 9,
);

public function __construct(array $attributes = array())
{
    $this->setRawAttributes($this->defaults, true);
    parent::__construct($attributes);
}

我建议将此作为 PR,因此我们不需要在每个模型中声明此构造函数,并且可以通过简单地$defaults在模型中声明数组来轻松应用...


更新

正如 cmfolio 所指出的,实际的答案非常简单

只需覆盖$attributes属性!像这样:

protected $attributes = array(
   'quantity' => 9,
);

此处讨论了该问题。

于 2013-09-11T17:57:11.563 回答
7

我知道这真的很老了,但我刚刚遇到了这个问题,并且能够使用这个网站解决这个问题。

将此代码添加到您的模型

protected static function boot()
{
   parent::boot();

   static::creating(function ($model) {
        $model->user_id = auth()->id();
    });
}

更新/免责声明

此代码有效,但它会覆盖常规的 Eloquent 模型creating事件

于 2018-10-23T15:34:29.423 回答
0

使用构造设置属性值

  public function __construct()
    {
        $this->attributes['locale'] = App::currentLocale();
    }
于 2021-05-03T22:15:56.270 回答
0

我将它用于 Laravel 8(静态和动态更改属性)

<?php

namespace App\Models\Api;

use Illuminate\Database\Eloquent\Model;

class Message extends Model
{
    /**
     * Indicates if the model should be timestamped.
     *
     * @var bool
     */
    public $timestamps = false;


    protected static function defAttr($messages, $attribute){

        if(isset($messages[$attribute])){
            return $messages[$attribute];
        }

        $attributes = [ 
            "password" => "123",
            "created_at" => gmdate("Y-m-d H:i:s"),
        ];

        return $attributes[$attribute];
    }
    

    /**
     * The "booted" method of the model.
     *
     * @return void
     */
    protected static function booted()
    {
        static::creating(function ($messages) {
            $messages->password = self::defAttr($messages, "password");
            $messages->created_at = self::defAttr($messages, "created_at");
        });
    }

}
于 2021-12-12T15:33:20.513 回答