有没有办法在Laravel中检索具有所有属性的模型,即使它们为null?似乎只返回属性不为null的模型。
这样做的原因是,如果模型中存在属性,则我有一个函数可以从数组更新模型属性。在设置模型之前,我使用property_exists()函数检查模型是否具有特定属性。数组键和模型属性应该匹配,因此可以正常工作。
如果模型已经设置了属性,则可以正常工作,因为该属性存在并从数组中获取值。但是,如果该属性以前为空,则不会更新或设置任何内容,因为该属性未通过property_exists()检查。
最终发生的是,我只有一个属性数组,然后是两个模型。然后运行我的setter函数,传入属性数组,并在单独的调用中传递每个对象。如果模型具有匹配的属性,则会对其进行更新。
这是两种方法。一种方法是在模型中定义默认属性值。
protected $attributes = ['column1' => null, 'column2' => 2];
然后,您可以使用该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;
}
基本上,如果未设置属性,则它将在该属性后附加一个空值,并将其作为数组返回给您。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句