获取具有所有属性的Laravel模型 [英] Get Laravel Models with All Attributes

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

问题描述

有没有一种方法可以在Laravel中检索具有所有属性的模型,即使它们为null?似乎只返回属性不为null的模型.

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函数,传入attributes数组,并在单独的调用中传递每个对象.如果模型具有匹配的属性,则会对其进行更新.

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模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆