有没有办法在Laravel中检索具有所有属性的模型,即使它们是空的?它似乎只返回一个非空属性的模型。
这样做的原因是,如果模型中存在属性,我有一个将从数组更新模型属性的函数。在设置之前,我使用property_exists()函数检查模型是否具有特定属性。数组键和模型属性应该匹配,这就是它的工作原理。
如果模型已经设置了属性,它可以正常工作,因为该属性存在并从数组中获取值。但是如果该属性以前为null,则不会更新或设置任何内容,因为它未通过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;
}
基本上,如果尚未设置该属性,则会向该属性追加一个空值,并将其作为数组返回给您。
$model->getAttributes();
上面将返回一个原始属性数组(存储在数据库表中)
$model->toArray()
上面将返回所有模型的原始,变异(如果使用)和附加属性
希望它会有所帮助!!
更新:
如果您在实例化之后尝试执行此操作,请执行以下操作:
$model = new Model;
那么请与Thomas Kim的回答不同。
除此以外:
你可以使用 toArray()
要么 getArributes()
模型实例上的方法,它将返回包括空值在内的所有属性。然后你可以使用 array_key_exists
去检查。
像这样:
if (array_key_exists('foo', $model->getAttributes())) {
$model->foo = 'new value';
}
如果您要明确声明所需的所有字段,该怎么办?
public function getSomeModelFromArray(Request $request)
{
// This will only give back the columns/attributes that have data.
// NULL values will be omitted doing it this way.
//$model = $request->all();
// However by declaring all the attributes I want I can get back
// columns even if the value is null. Additional filtering can be
// added on if you still want/need to massage the data.
$model = $request->all([
'id',
'attr1',
'attr2',
'attr3',
//...
]);
//...
return $model;
}
非常通用的例子,但希望有人会发现这很有用。