创建具有关系的雄辩实例 [英] Create new eloquent instance with relationships

查看:100
本文介绍了创建具有关系的雄辩实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何创建具有关系的雄辩模型的新实例.

How do I create a new instance of an eloquent model with relationships.

这是我正在尝试的:

$user = new User();
$user->name = 'Test Name';
$user->friends()->attach(1);
$user->save();

但是我得到

Call to undefined method Illuminate\Database\Query\Builder::attach()

推荐答案

尝试在save之后附加朋友,因为attach()方法需要在父模型上存在ID. (通常)在保存模型之前(在数据库中创建该模型的主键或其他标识符时)才会生成ID:

Try to attach friend after save since the attach() method needs an ID to exist on the parent model. ID's aren't (usually) generated until model is saved (when a primary key or other identifier for that model is created in the database) :

$user = new User();
$user->name = 'Test Name';
$user->save();

$user->friends()->attach(1);

希望这会有所帮助.

这篇关于创建具有关系的雄辩实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆