简体   繁体   English

从数据库架构设置默认属性值

[英]Setting default attribute values from database schema

Is it possible for Laravel to set default attribute values for model from database, when creating object by new Model or Model::create() ? 当通过new ModelModel::create()创建对象时,Laravel是否可以为数据库的模型设置默认属性值?

For example, I have table clients with some columns (name, sex, birthday, device, os, etc). 例如,我的表clients带有一些列(名称,性别,生日,设备,操作系统等)。 I'm doing 我正在做

$client = new Client::create(['name' => 'John Doe']);

and want $client object has all attributes, not only name. 并希望$client对象具有所有属性,而不仅仅是名称。 dd($client->toArray()); returns 回报

array:1 [▼
  "name" => "John Doe",
  "id" => 1
]

But dd(Client::find(1) returns 但是dd(Client::find(1)返回

array:11 [▼
  "id" => 1
  "name" => "John Doe"
  "birthday" => null
  "sex" => 1
  "device" => ""
  "os" => ""
]

Yes, i could set protected $attributes property in model, but it is not what i'm looking for. 是的,我可以在模型中设置protected $attributes属性,但这不是我想要的。 I want this to be fetched from database schema. 我希望这是从数据库架构中获取的。

You could override the __construct() function to merge in any missing attributes. 您可以重写__construct()函数以合并任何缺少的属性。

So in your model... 因此,在您的模型中...

protected $defaults = [
    'sex' => 1,
    'device' => 'AAA',
    'os' => 'BBB',
];

public function __construct($attributes = [])
{
    $attributes = array_merge($this->defaults, $attributes);

    parent::__construct($attributes);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM