Framework: Update existing Eloquent model from either side of a one-to-many relationship.

Created on 5 Jun 2013  路  6Comments  路  Source: laravel/framework

Why isn't it possible to update a relationship for a one-to-many (or one-to-one) relationship from both sides of the relationship? Given this set-up:

class Account extends Eloquent
{
public function users()
{
return $this->hasMany('User');
}
}

class User extends Eloquent
{
public function account()
{
return $this->belongsTo('Account');
}
}

it should be possible to do both:
Account::find(10)->users()->save(User::find(1)); // this works
User::find(1)->account()->save(Account::find(10)); // this doesn't work

to assign account 10 to user 1.

But only the first one works. The other one is generating an error: "Call to undefined method Illuminate\Database\Query\Builder::save()"

Shouldn't it be possible to save or update/attach a relationship from both sides of the relation when it has been explicitly set-up in the models via hasMany() and belongsTo()?

Most helpful comment

I am wondering if there's a method like 'attach' for one-to-many relation to update multiple entries from 'many' end of the relation.

For example I have Ingredients and IngredientTypes in one-to-many relation. I have ingredients already in the DB. So how can I associate multiple Ingredients together with a certain IngredientType.

All 6 comments

$user = User::find(1);

$user->account()->associate(Account::find(10));

$user->save();

If I would have just found this in the docs... THANKS!

Just pushed an update to docs.

awesome! you rock!

I am wondering if there's a method like 'attach' for one-to-many relation to update multiple entries from 'many' end of the relation.

For example I have Ingredients and IngredientTypes in one-to-many relation. I have ingredients already in the DB. So how can I associate multiple Ingredients together with a certain IngredientType.

$user = User::find($id);
$user->update($array);
$user->email()->delete();
$user->email()->createMany($array['emails']);

Was this page helpful?
0 / 5 - 0 ratings

Related issues

RomainSauvaire picture RomainSauvaire  路  3Comments

ghost picture ghost  路  3Comments

PhiloNL picture PhiloNL  路  3Comments

progmars picture progmars  路  3Comments

iivanov2 picture iivanov2  路  3Comments