如何在 Laravel Eloquent 中插入具有许多属于关系的记录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27765377/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 10:38:21  来源:igfitidea点击:

How to insert record with many belongsTo relations in Laravel Eloquent

phplaravelormeloquent

提问by TheJohnny

I am trying to insert record in Eloquent way.

我正在尝试以 Eloquent 方式插入记录。

It is clear in basic cases. For example if I have a Blog with Posts and each post belongs to a User I can do this:

在基本情况下很清楚。例如,如果我有一个带有帖子的博客并且每个帖子都属于一个用户,我可以这样做:

$post = new Post;
$post->content = 'Post content';
$user->posts()->save($post);

But how should I do this if my Post belongs to User, Category and Group at the same time?

但是如果我的帖子同时属于用户、类别和组,我该怎么做?

My first idea was to do it this way:

我的第一个想法是这样做:

$post = new Post;
$post->content = 'Post content';
$user->posts()->save($post);
$group->posts()->associate($post);
$cat->posts()->associate($post);

But it doesn't work, because group id and category id are null when I save it to the DB and it is not allowed.

但它不起作用,因为当我将其保存到数据库时,组 id 和类别 id 为空,这是不允许的。

What I am doing now is:

我现在正在做的是:

$post = new Post;
$post->content = 'Post content';
$post->group = $group->id;
$post->category = $cat->id;
$user->posts()->save($post);

But I don't think it is the right way.

但我认为这不是正确的方法。

Could someone point me in the right direction?

有人能指出我正确的方向吗?

采纳答案by lukasgeiter

You're using associatethe wrong way around. You have to call it on the belongsTorelation side not the hasMany.

你用associate错了方法。您必须在belongsTo关系方面而不是hasMany.

Try this:

尝试这个:

$post = new Post;
$post->content = 'Post content';
$post->category()->associate($cat);
$post->group()->associate($group);
$user->posts()->save($post);