Laravel 4 中如何插入相关的多态模型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24642048/
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-09-14 09:47:30  来源:igfitidea点击:

How do you insert related polymorphic models in Laravel 4

phplaravellaravel-4eloquent

提问by Anthony

In Laravel 4 I have a "Meta" model that can be associated to any object via an "object_id" and "object_type" property. For example:

在 Laravel 4 中,我有一个“元”模型,可以通过“object_id”和“object_type”属性关联到任何对象。例如:

id: 1
object_id: 100
object_type: User
key: favorite_ice_cream
value: Vanilla

I have this working correctly via morphTo() and morphMany() as described in http://laravel.com/docs/eloquent#polymorphic-relations, so I can pull the user and all of his meta via:

我通过 morphTo() 和 morphMany() 正常工作,如http://laravel.com/docs/eloquent#polymorphic-relations 中所述,所以我可以通过以下方式拉用户和他的所有元数据:

$user = User::with('meta')->find(100);

$user = User::with('meta')->find(100);

What I'm trying to figure out now is: Is there an easy way to save meta to my user? As in:

我现在想弄清楚的是:有没有一种简单的方法可以将元数据保存给我的用户?如:

$user = User::find(100);
$user->meta()->save(['key' => 'hair_color', 'value' = 'black']);

Whatever does the saving would need to properly set the object_id and object_type on the meta. Since I've defined the relationships in the models, I'm not sure if that would be done automatically or not. I randomly tried it a few different ways but it crashed each time.

无论保存做什么,都需要在元数据上正确设置 object_id 和 object_type。由于我已经在模型中定义了关系,我不确定这是否会自动完成。我随机尝试了几种不同的方法,但每次都崩溃了。

回答by Jarek Tkaczyk

savemethod on the MorphManytakes related Model as param, not an array.

save方法MorphMany将相关模型作为参数,而不是数组。

It will always correctly set the foreign key, and model type for polymorphic relations. Obviously you need to save the parent model first.

它将始终正确设置多态关系的外键和模型类型。显然,您需要先保存父模型。

// Meta morphTo(User)
$user = User::find($id);

$meta = new Meta([...]);
$user->meta()->save($meta);

// or multiple
$user->meta()->saveMany([new Meta([...], new Meta[...]);

attachon the other hand is different method that works on belongsToManyand m-m polymorphic relations and it does notdo the same, but those relations also use save.

attach在另一方面是不同的方法对作品belongsToMany和多态毫米的关系,它并没有这样做,但这些关系也可以使用save

// User belongsToMany(Category)
$user = User::find($id);
$user->categories()->save(new Category([...]));

// but attach is different
$user->categories()->attach($catId); // either id

$category = Category::find($catId);
$user->categories()->attach($category); // or a Model

// this will not work
$user->categories()->attach(new Category([...]));