anderlaini
anderlaini

Reputation: 1831

Cannot save hasOne() model relationship

Visitor model:

public function group()
{
  return $this->belongsTo('MyApp\Models\VisitorGroup', 'group_id');
}

VisitorGroup model:

public function visitors()
{
  return $this->hasMany('MyApp\Models\Visitor');
}

So then I'm trying to create some Visitors for a group:

$mygroup = VisitorGroup::whereRaw('name LIKE "%mygroup%"')->first();
foreach(range(1, 10) as $i)
{
  $v = Visitor::create(array('name' => 'Homer simpson'));
  $v->group()->save($mygroup); // HERE trying to add this visitor to the group
}

But I'm getting this error:

[BadMethodCallException]
Call to undefined method Illuminate\Database\Query\Builder::save()

Am I doing something wrong?

Upvotes: 0

Views: 107

Answers (1)

lukasgeiter
lukasgeiter

Reputation: 153150

That's because BelongsTo has no save() method. However it has an associate() method which is probably what you're looking for. Not that you have to explicitly save the model afterwards:

$v = Visitor::create(array('name' => 'Homer simpson'));
$v->group()->associate($mygroup);
$v->save();

Or you could just set the foreign key manually when creating to save db queries:

$v = Visitor::create(array('name' => 'Homer simpson', 'group_id' => $mygroup->id));

Or the probably most elegant way:

$mygroup->visitors()->create(array('name' => 'Homer simpson'));

Upvotes: 1

Related Questions