简体   繁体   English

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

[英]How do you insert related polymorphic models in Laravel 4

In Laravel 4 I have a "Meta" model that can be associated to any object via an "object_id" and "object_type" property. 在Laravel 4中,我有一个“元”模型,可以通过“ object_id”和“ object_type”属性将其与任何对象关联。 For example: 例如:

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: http://laravel.com/docs/eloquent#polymorphic-relations中所述 ,我可以通过morphTo()和morphMany()正常工作,因此我可以通过以下方式拉出用户及其所有元数据:

$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? 我现在要弄清楚的是:是否有一种简单的方法可以将meta保存到我的用户? 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. 保存所做的任何事情都需要在元数据上正确设置object_id和object_type。 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. 我随机尝试了几种不同的方法,但是每次都崩溃了。

save method on the MorphMany takes related Model as param, not an array. MorphMany上的save方法将相关的Model作为参数,而不是数组。

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[...]);

attach on the other hand is different method that works on belongsToMany and mm polymorphic relations and it does not do 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([...]));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM