Laravel 4: a lot for many (insert)

I have these tables in the database:

[posts, cats (categories), posts_cats (pivote)] 

the relationship between columns and cats is a lot for many

I declared the relation in model classes:

 //Post.php public function cats() { return $this->belongsToMany('cats'); } //Cats.php public function post() { return $this->belongsToMany('posts'); } 

The question is how to insert a new message with multiple categories?

thanks,

+6
source share
3 answers

Say you know the message id, then you can attach one cat as follows:

 Post::find($post_id)->cats()->attach($cat_id); 

Or attach some cats, like this:

 $cat_ids = array(1,2,3,4); Post::find($post_id)->cats()->attach($cat_ids); 

If you got the Post model object in a variable, say $ post:

 $post->cats()->attach($cat_id); // Or with multiple $cat_ids = array(1,2,3,4); $post->cats()->attach($cat_ids); 

If you have one category as a model object, say $ model:

 $post->cats()->save($model); 

Stay tuned for @Gadoma's answers. This is not the case, but if you want to add categories to a post that already has categories, you should use attach () instead of sync (). Sync () will delete all others that were not provided to it during use.

Editing:
Therefore, if you create new mail, you are probably doing something like this:

 $post = new Post; $post->title = 'The title'; $post->something_else = 'Lorem'; $post->save(); //So now you have both the model object (the $post variable) and the id ($post->id). $post->cats()->attach($cat_ids); 
+15
source

When you insert a message, then repeat over the categories and attach them to the new message. Something like that:

 // $categories is an array of the categories to attach foreach ($category_id in $categories) { // Get a category object $category = CategoryModel::find($category_id); // $post is the new post $post->cats()->attach($category); } 

Hope this helps you.

+1
source

From the docs http://laravel.com/docs/eloquent#inserting-related-models

Insert similar models (many of many)

[...]

You can also use the synchronization method to attach related models. The synchronization method takes an array of identifiers to place on the pivot table. After this operation is completed, only the identifiers in the array will be on the intermediate table for the model:

And an example code:

 $post = new Post(array('field1'=>'value1','fieldN'=>'valueN')) //example create new post $categoryIds = array(1,3,4,5); //ids of (cats) categories you want the post to go into $post->cats()->sync($categoryIds); //synchronise pivot table content with $categoryIds 
+1
source

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


All Articles