ken*_*in9 16 php model laravel eloquent laravel-5.1
有没有办法在Laravel中检索具有所有属性的模型,即使它们是空的?它似乎只返回一个非空属性的模型.
原因是我有一个函数,如果模型中存在属性,将从数组更新模型属性.在设置之前,我使用property_exists()函数检查模型是否具有特定属性.数组键和模型属性应该匹配,因此它的工作方式.
如果模型已经设置了属性,它可以正常工作,因为该属性存在并从数组中获取值.但是,如果属性以前为null,则不会更新或设置任何内容,因为它无法通过property_exists()检查.
最终发生的事情是我有一个属性数组,然后可能有两个模型.我运行我的setter函数,传入attributes数组,并在每个单独的调用中传递每个对象.如果模型具有匹配属性,则会更新.
Tho*_*Kim 18
这有两种方法可以做到这一点.一种方法是在模型中定义默认属性值.
protected $attributes = ['column1' => null, 'column2' => 2];
Run Code Online (Sandbox Code Playgroud)
然后,您可以使用该getAttributes()方法获取模型的属性.
如果你不想设置默认属性,我写了一个应该有效的快速方法.
public function getAllAttributes()
{
$columns = $this->getFillable();
// Another option is to get all columns for the table like so:
// $columns = \Schema::getColumnListing($this->table);
// but it's safer to just get the fillable fields
$attributes = $this->getAttributes();
foreach ($columns as $column)
{
if (!array_key_exists($column, $attributes))
{
$attributes[$column] = null;
}
}
return $attributes;
}
Run Code Online (Sandbox Code Playgroud)
基本上,如果尚未设置该属性,则会向该属性追加一个空值,并将其作为数组返回给您.
小智 6
$model->getAttributes();
Run Code Online (Sandbox Code Playgroud)
上面将返回一个原始属性数组(存储在数据库表中)
$model->toArray()
Run Code Online (Sandbox Code Playgroud)
上面将返回所有模型的原始,变异(如果使用)和附加属性
希望它会有所帮助!!
| 归档时间: |
|
| 查看次数: |
27992 次 |
| 最近记录: |