Create new eloquent instance with relationships

2019-07-15 04:20发布

问题:

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.