問(wèn)題描述
有沒(méi)有辦法在 Laravel 中檢索具有所有屬性的模型,即使它們?yōu)榭?它似乎只返回一個(gè)屬性不為空的模型.
Is there a way to retrieve a model in Laravel with all the attributes, even if they're null? It seems to only return a model with the attributes that aren't null.
這樣做的原因是我有一個(gè)函數(shù)可以更新數(shù)組中的模型屬性,如果模型中存在這些屬性.在設(shè)置模型之前,我使用 property_exists() 函數(shù)檢查模型是否具有特定屬性.數(shù)組鍵和模型屬性應(yīng)該匹配,所以它是如何工作的.
The reason for this is that I have a function that will update the model attributes from an array, if the attributes exists in the model. I use the property_exists() function to check the model if it has a particular attribute before setting it. The array key and model attribute are expected to match, so that's how it works.
如果模型已經(jīng)設(shè)置了屬性,它就可以正常工作,因?yàn)閷傩源嬖诓臄?shù)組中獲取值.但是,如果該屬性之前為空,則不會(huì)更新或設(shè)置任何內(nèi)容,因?yàn)樗赐ㄟ^(guò) property_exists() 檢查.
It works fine if the model already has the attributes set, because the attribute exists and takes the value from the array. But nothing will get updated or set if the attribute was previously null, because it fails the property_exists() check.
最終發(fā)生的是我有一個(gè)單一的屬性數(shù)組,然后可能是兩個(gè)模型.我運(yùn)行我的 setter 函數(shù),傳入屬性數(shù)組,并在單獨(dú)的調(diào)用中傳遞每個(gè)對(duì)象.如果模型具有匹配的屬性,則會(huì)更新.
What's ultimately happening is that I have a single array of attributes, and then perhaps two models. And I run my setter function, passing in the attributes array, and each of the objects in separate calls. If the model has a matching property, it gets updated.
推薦答案
這里有兩種方法可以做到這一點(diǎn).一種方法是在模型中定義默認(rèn)屬性值.
Here are two ways to do this. One method is to define default attribute values in your model.
protected $attributes = ['column1' => null, 'column2' => 2];
然后,您可以使用 getAttributes()
方法來(lái)獲取模型的屬性.
Then, you can use the getAttributes()
method to get the model's attributes.
如果你不想設(shè)置默認(rèn)屬性,我寫(xiě)了一個(gè)應(yīng)該有效的快速方法.
If you don't want to set default attributes though, I wrote up a quick method that should work.
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;
}
基本上,如果尚未設(shè)置該屬性,則會(huì)向該屬性附加一個(gè)空值并將其作為數(shù)組返回給您.
Basically, if the attribute has not been set, this will append a null value to that attribute and return it to you as an array.
這篇關(guān)于獲取所有屬性的 Laravel 模型的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!