php 获取所有属性的 Laravel 模型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33512184/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:31:35  来源:igfitidea点击:

Get Laravel Models with All Attributes

phplaravelmodeleloquentlaravel-5.1

提问by kenshin9

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.

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

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.

如果模型已经设置了属性,它就可以正常工作,因为属性存在并从数组中获取值。但是,如果该属性以前为空,则不会更新或设置任何内容,因为它未通过 property_exists() 检查。

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.

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

回答by Thomas Kim

Here are two ways to do this. One method is to define default attribute values in your model.

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

protected $attributes = ['column1' => null, 'column2' => 2];

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

然后,您可以使用该getAttributes()方法来获取模型的属性。

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.

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

回答by Mahesh Yadav

$model->getAttributes();

Above will return an array of raw attributes (as stored in the database table)

以上将返回一组原始属性(存储在数据库表中)

$model->toArray() 

Above will return all the model's raw, mutated(if used), and appended attributes

以上将返回模型的所有原始、变异(如果使用)和附加属性

Hope it will helpful!!

希望它会有所帮助!!

回答by tam5

Update:

更新:

If you are trying to do this after instantiating like so:

如果您在像这样实例化后尝试执行此操作:

$model = new Model;

then please differ to Thomas Kim's answer.

那么请与 Thomas Kim 的回答不同。

Otherwise: You could use the toArray()or getArributes()method on the model instance, that would give back all the attributes including nulls. Then you can use array_key_existsto check.

否则:您可以在模型实例上使用toArray()orgetArributes()方法,这将返回包括空值在内的所有属性。然后就可以array_key_exists用来检查了。

Like so:

像这样:

if (array_key_exists('foo', $model->getAttributes())) {
    $model->foo = 'new value';
}

回答by Rockin4Life33

What if you were to explicitly declare all the fields you want back.

如果您要显式声明想要返回的所有字段,该怎么办?

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

Pretty generic example but hopefully someone will find this useful.

非常通用的例子,但希望有人会发现这很有用。

回答by Omni Titan

I have this snippet on my other project to load all model attributes and relation.

我在我的另一个项目中有这个片段来加载所有模型属性和关系。

public function forModel($with)
{
    $this->load($with);

    $attributes = $this->toArray();

    // Normalize Null Relation To Empty Model
    foreach ($attributes as $key => $value) {
        if (
            is_null($value) && 
            method_exists($this, Str::camel($key)) && 
            $this->{Str::camel($key)}() instanceOf \Illuminate\Database\Eloquent\Relations\Relation
        ) {

            $relation = $this->{Str::camel($key)}();
            $model = $relation->getModel();
            $attributesForRelation = $model->getAttributes();
            foreach ($model->getFillable() as $column)
            {
                if (! array_key_exists($column, $attributesForRelation))
                {
                    $attributesForRelation[$column] = null;
                }
            }

            $attributes[$key] = $attributesForRelation;
        } else {
            $attributes[$key] = $value;
        }
    }

    return $attributes;
}