Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 877
Anthony Avatar asked Jul 08 '14 21:07

Anthony


1 Answers

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 m-m 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([...]));
like image 81
Jarek Tkaczyk Avatar answered Oct 15 '22 01:10

Jarek Tkaczyk