将数据插入到 Laravel 中的数据透视表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24547376/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Insert data to a pivot table in laravel
提问by saha
I have 3 tables: posts
, tags
, post_tag
.
我有 3 个表:posts
, tags
, post_tag
。
Each Post
has many tags so I use hasMany
method for them. But when I choose for example 3 tags in my dropdown list, I can't add them to post_tag
and as the result I can't select and show each post's tags.
每个Post
都有很多标签,所以我hasMany
对它们使用方法。但是,当我在下拉列表中选择例如 3 个标签时,我无法将它们添加到其中,post_tag
因此我无法选择和显示每个帖子的标签。
My Post
model:
我的Post
型号:
class Post extends Eloquent{
public function tag()
{
return $this->hasMany('Tag');
}
}
My Tag
model:
我的Tag
型号:
class Tag extends Eloquent{
public function post()
{
return $this->belongsToMany('Post');
}
}
}
And my postController
:
而我的postController
:
class postController extends BaseController{
public function addPost(){
$post=new Post;
$post_title=Input::get('post_title');
$post_content=Input::get('post_content');
$tag_id=Input::get('tag');
$post->tag()->sync($tag_id);
$post->save();
I expect to save this post_id
save to post_tag
table with its tag ids,
but it doesn't work. Thanks for your time.
我希望将此post_id
保存保存到post_tag
带有标签 ID 的表中,但它不起作用。谢谢你的时间。
采纳答案by alexrussell
You have a basic idea right, but there are a few issues with your code. Some are stopping it from working and some are just conventional issues.
您的基本想法是正确的,但是您的代码存在一些问题。有些是阻止它工作,有些只是常规问题。
First off, this is a belongsTomany
relationship (you have a pivot table) so you must define both sides of the relationship as belongsToMany
(even if hasMany
is the way you think about one or both of the side of it). This is because Laravel expects a certain database structure with the two different relationship types.
首先,这是一个belongsTomany
关系(您有一个数据透视表),因此您必须将关系的双方定义为belongsToMany
(即使hasMany
是您对其中一方或双方的看法)。这是因为 Laravel 期望具有两种不同关系类型的特定数据库结构。
Another issue (that you found yourself) is that you are adding the tags to the relation (via ->tag()->sync()
before you've actually saved the post. You must first save the post (so that laravel knows what ID to add to the pivot table for post_id
) and then add the relations. If you are worried about the tags part failing and then having an inconsistent database you should use transactions.
另一个问题(您自己发现的)是您将标签添加到关系中(通过->tag()->sync()
在您实际保存帖子之前。您必须首先保存帖子(以便 Laravel 知道要添加到数据透视表的 ID 为post_id
)然后添加关系。如果你担心标签部分失败,然后数据库不一致,你应该使用事务。
Finally, the 'convention' errors you have is that a belongs-to-many relationship, by definition, involves collections of results. As such, tag
and post
shoudl be tags
and posts
respectively.
最后,您遇到的“约定”错误是属于多关系,根据定义,涉及结果的集合。这样,tag
和post
shoudl是tags
和posts
分别。
So here's my rewritten version of your code:
所以这是我重写的代码版本:
class Post extends Eloquent
{
public function tags()
{
return $this->belongsToMany('Tag');
}
}
class Tag extends Eloquent
{
public function posts()
{
return $this->belongsToMany('Post');
}
}
class PostController extends BaseController
{
public function addPost()
{
// assume it won't work
$success = false;
DB::beginTransaction();
try {
$post = new Post;
// maybe some validation here...
$post->title = Input::get('post_title');
$post->content = Input::get('post_content');
if ($post->save()) {
$tag_ids = Input::get('tags');
$post->tags()->sync($tag_ids);
$success = true;
}
} catch (\Exception $e) {
// maybe log this exception, but basically it's just here so we can rollback if we get a surprise
}
if ($success) {
DB::commit();
return Redirect::back()->withSuccessMessage('Post saved');
} else {
DB::rollback();
return Redirect::back()->withErrorMessage('Something went wrong');
}
}
}
Now a lot of that controller code centres around the transaction stuff - if you don't care too much about that then you're all good to remove it. Also there are several ways to do that transaction stuff - I've gone with one that's not ideal but gets the point across in a minimal amount of code.
现在,很多控制器代码都围绕着事务处理——如果你不太关心它,那么你可以将它删除。此外,还有几种方法可以完成这些事务——我采用了一种并不理想但用最少的代码就可以解决问题的方法。
回答by Boston Kenne
To insert you data into pivot table name diplome_user, just follow my example: my pivot table looking like:
要将您的数据插入数据透视表名称diplome_user,只需按照我的示例:我的数据透视表如下所示:
//this is Diplome Model
class Diplome extends Model
{
public function users()
{
return $this->belongsToMany('App\User','diplome_user')->withPivot('etablissement', 'annee', 'mention');;
}
}
now inside you my DiplomeController, I'm able to make this query:
现在在我的 DiplomeController 中,我可以进行以下查询:
$user = Auth::user();
because I need a user, I just take the connected one, after it, I create one instance of Diplome like:
因为我需要一个用户,所以我只需要连接的用户,在它之后,我创建一个 Diplome 实例,例如:
$diplome = new Diplome();
$diplome->libelle = "the name";
$diplome->decription= "description of the ...";
$diplome->save();
now the most important step is:
现在最重要的步骤是:
$diplome->users()->attach($user, ['etablissement'=> 'bib',
'annee'=>'2015',
'mention'=>'AB',
]);
Here is the result:
结果如下:
回答by Joel Hinz
The sync()
method wants an array. It should work if you just put the tag id within one, like so:
该sync()
方法需要一个数组。如果您只是将标签 ID 放在一个内,它应该可以工作,如下所示:
$post->tag()->sync([$tag_id]);