沃梦达 / 编程问答 / php问题 / 正文

获取所有属性的 Laravel 模型

Get Laravel Models with All Attributes(获取所有属性的 Laravel 模型)

本文介绍了获取所有属性的 Laravel 模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在 Laravel 中检索具有所有属性的模型,即使它们为空?它似乎只返回一个属性不为空的模型.

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.

这样做的原因是我有一个函数可以更新数组中的模型属性,如果模型中存在这些属性.在设置模型之前,我使用 property_exists() 函数检查模型是否具有特定属性.数组键和模型属性应该匹配,所以它是如何工作的.

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.

如果模型已经设置了属性,它就可以正常工作,因为属性存在并从数组中获取值.但是,如果该属性之前为空,则不会更新或设置任何内容,因为它未通过 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.

最终发生的是我有一个单一的属性数组,然后可能是两个模型.我运行我的 setter 函数,传入属性数组,并在单独的调用中传递每个对象.如果模型具有匹配的属性,则会更新.

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.

推荐答案

这里有两种方法可以做到这一点.一种方法是在模型中定义默认属性值.

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() 方法来获取模型的属性.

Then, you can use the getAttributes() method to get the model's attributes.

如果你不想设置默认属性,我写了一个应该有效的快速方法.

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;
}

基本上,如果尚未设置该属性,则会向该属性附加一个空值并将其作为数组返回给您.

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.

这篇关于获取所有属性的 Laravel 模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:获取所有属性的 Laravel 模型

基础教程推荐