If I try declaring a property, like this:

public $quantity = 9;

...it doesn't work, because it is not considered an "attribute", but merely a property of the model class. Not only this, but also I am blocking access to the actually real and existent "quantity" attribute.

那我该怎么办呢?

推荐答案

这就是我现在正在做的:

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

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

I will suggest this as a PR so we don't need to declare this constructor at every Model, and can easily apply by simply declaring the $defaults array in our models...


UPDATE:

正如cmfolio所指出的,the actual ANSWER is quite simple:

Just override the $attributes property! Like this:

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

here人讨论了这个问题.

Laravel相关问答推荐

在Laravel Lumen中迭代连接查询数据

提交表格后如何在Livewire 3中调度模式窗口?

在postgres/mysqlс中,我可以定义基于json字段的唯一索引吗?

在Laravel Sail Docker环境中的PHPMyAdmin中出现`Out of Memory‘错误

使用 Laravel 10 在 Blade 中添加成功消息

如何让 Laravel 的 Collection 表现得像一个流?

当两个外键都在同一个表上时创建直通关系

我如何通过 laravel 在高图中针对不同的时间范围进行烛台数据分组

如何提取每组 groupBy 查询的唯一值?

在 Laravel 中清除 Routes&config:cache 后未定义的常量

自从 Laravel 使用 Vite 更新后,我无法运行npm run dev

不能在 laravel 中使用控制器名称,必须使用命名空间

Laravel init 查询多种用途

Laravel 5.1 是否与 PHP 7 兼容

有条件的Eager加载

在 Laravel 的 Homestead 中运行 PHPUnit

Laravel 字符串验证以允许空字符串

向 Laravel 重定向添加一个锚点

Laravel s3 多桶

Laravel 验证用户名不允许有空格