Laravel雄辩的忽略属性,如果在插入过程中不在表中 [英] Laravel Eloquent ignore attribute if not in table during insert
问题描述
我有一个Foo模型,它对应于具有以下各列的表.
I have a model Foo that corresponds to a table with the following columns.
id
说明
user_id
id
description
user_id
我要分别设置Foo模型的属性(无质量分配)
I'm setting the attributes of the Foo model individually (no mass assignment)
$foo = new Foo;
$foo->id = 1;
$foo->description = "hello kitty";
$foo->user_id = 55;
//...
$ foo被发送到另一个类以进行其他处理,但是由于该类需要更多信息,因此我想将其简单地添加到$ foo模型中.
$foo is sent to another class for additional processing, but because that class needs a bit more information, I would like to simply add it to the $foo model.
//...
$foo->bar = $additional_information;
Event::fire(DoStuffWithFoo($foo));
$foo->save(); //error
问题是当我$foo->save()
时,它抱怨bar
不是列.
the problem is when I $foo->save()
, it complains that bar
isn't a column.
我知道保存之前可以unset($foo->bar);
,但是...
I know I can unset($foo->bar);
before saving, but...
是否可以告诉Eloquent忽略任何不相关的属性?
Is it possible to tell Eloquent to simply ignore any non relevant attributes?
推荐答案
只需将$bar
作为属性添加到foo类中即可:
Just add $bar
as an attribute in your foo class:
class Foo extends Model
{
public $bar;
//...
现在您可以使用save()
,Laravel不会尝试将bar
存储在数据库中.
now you can use save()
and Laravel will not try to store bar
in the DB.
说明:
如果在模型上调用save()
,则仅将数组$model->attributes
中的那些属性保存到数据库中.如果将$bar
定义为类Foo
中的属性,则$foo->bar ="xyz"
将永远不会以数组$model->attributes
结尾.
If you call save()
on a model, only those attributes that are in the array $model->attributes
will be saved to the database. If you define $bar
as an attribute in the class Foo
, then $foo->bar ="xyz"
will never end up in the array $model->attributes
.
但是,如果尚未为Foo
声明这样的属性,则会调用__set()
,因为您
However, if you do not have declared such an attribute for Foo
, then __set()
is called because you try to save something in an inaccessible property.
您可以签出Laravel\Illuminate\Database\Eloquent\Model.php
:
/**
* Dynamically set attributes on the model.
*
* @param string $key
* @param mixed $value
* @return void
*/
public function __set($key, $value)
{
$this->setAttribute($key, $value);
}
基本上可以调用
$this->attributes[$key] = $value;
来自Laravel\Illuminate\Database\Eloquent\Concerns\HasAttributes.php
.
现在$foo->bar ="xyz"
最终会在$foo->attribute['bar']
中变成蜜蜂,这就是为什么save()
与..this column does not exists..
崩溃的原因.
Now $foo->bar ="xyz"
will end up beeing in $foo->attribute['bar']
and this is why save()
crashes with ..this column does not exists..
.
这篇关于Laravel雄辩的忽略属性,如果在插入过程中不在表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!