简体   繁体   中英

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. 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:

$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.

save method on the MorphMany takes related Model as param, not an array.

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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