Create new eloquent instance with relationships

扶醉桌前 提交于 2020-01-15 03:40:14

问题


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

This is what I am trying:

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

But I get

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

回答1:


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);

Hope this helps.



来源:https://stackoverflow.com/questions/34404661/create-new-eloquent-instance-with-relationships

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!