How do you insert related polymorphic models in Laravel 4

In Laravel 4, I have a “Meta” model that can be associated with any object through the object_id and object_type properties. For instance:

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

I work correctly with morphTo () and morphMany (), as described in http://laravel.com/docs/eloquent#polymorphic-relations , so I can pull the user and all of its meta through:

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

Now I'm trying to understand: is there an easy way to save meta for my user? How in:

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

Regardless of what you need to save, you need to set object_id and object_type correctly in the meta. Since I defined relationships in models, I’m not sure if this will be done automatically or not. I accidentally tried several methods, but each time it crashed.

+4
source share
1 answer

saveThe method MorphManyaccepts the associated model as param, not an array.

It will always correctly set the foreign key and model type for polymorphic relationships. 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, , , belongsToMany mm, , 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([...]));
+11

Source: https://habr.com/ru/post/1547654/


All Articles