问题 获取具有所有属性的Laravel模型


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

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

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

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


5661
2017-11-04 01:28


起源

尝试$ model-> getAttributes() - Lê Trần Tiến Trung
对我的回答没有想法? - Thomas Kim


答案:


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

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

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


12
2017-11-04 06:19



如果目标是将空值设置为null,则最简单的方法是追加 ->nullable() 到迁移领域。您不需要编写新方法或在模型中设置它。据说这些都不是必要的 - tam5
目标是让他能够在尚未设置时获取所有属性,并且唯一的方法是将值设置为null(或其他一些默认值)。 - Thomas Kim
至少,因为我们无法看到任何代码,所以我假设他正在处理一个空实例,因为他说 getAttributes() 不管用。例如,像 $user = new User; $user->getAttributes(); 不会返回属性,因为它没有设置。 - Thomas Kim
啊,如果他打电话,你的确是对的 new User; 在这种情况下,我会更新我的答案,与你的不同 - tam5
谢谢!这使我朝着正确的方向前进。实际上,我并不需要模型上的每个属性。只有几个选择要更新,巧合的是,当我想到它时,也是在$ fillable数组中。所以我实际上能够使用$ fillable来检查模型是否应该具有该属性。 - kenshin9


$model->getAttributes();

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

$model->toArray() 

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

希望它会有所帮助!!


2
2018-02-28 13:45



这很好用,怎么会被投票呢? - Bjørnar Hagen


更新:

如果您在实例化之后尝试执行此操作,请执行以下操作:

$model = new Model;

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

除此以外: 你可以使用 toArray() 要么 getArributes() 模型实例上的方法,它将返回包括空值在内的所有属性。然后你可以使用 array_key_exists 去检查。

像这样:

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

0
2017-11-04 04:54



我尝试实例化一个新模型,当尝试其中一个函数时,我得到一个空数组。我认为应该预料到这一点。至少从getAttributes()的文档中,它说“获取模型上的所有当前属性”。 - kenshin9
你在项目中实例化了还是只是修补? - tam5
对不起,我没想到要提到这一点。我确实在我的项目中实例化了它。 - kenshin9
这对我来说非常奇怪。你可以发布你的代码吗? - tam5


如果您要明确声明所需的所有字段,该怎么办?

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

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


0
2017-07-27 20:09