简体   繁体   English

Laravel-保存多个模型

[英]Laravel - saving multiple models

Hy guys, i have a post table and a tags table also a post_tag pivot table in my DB. 大家好,我的数据库中有一个post表和一个tag表,还有一个post_tag数据透视表。

Everything works just fine, when i want to save a new post with one tags using this method: 当我想使用此方法使用一个标签保存新帖子时,一切工作正常。

$post->tags()->save($tag)

But when i have multiple tags, then of course the save method dies. 但是当我有多个标签时,当然保存方法会死掉。 So my question is how can i save multiple tags ? 所以我的问题是如何保存多个标签?

If your $tag is an array you can try something like: 如果您的$tag是一个数组,则可以尝试如下操作:

$tags = array(1,2,3,4);

$post->tags()->attach($tags);

The above method will add a tag_id 1,2,3,4 for that particular post. 上面的方法将为该特定帖子添加一个tag_id 1,2,3,4。

Another approach would be to use the saveMany() method which allows you to store an array of models. 另一种方法是使用saveMany()方法,该方法允许您存储模型数组。

$post->tags()->saveMany($arrayOfTagObjects);

I think that method is more straightforward since you pretty often work with collections (which you can easily convert into an array) or arrays anyways. 我认为该方法更直接,因为您经常使用集合(可以轻松地将其转换为数组)或数组。 So you don't need to extract the id's by yourself. 因此,您无需自己提取ID。

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

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