Framework: Troubles with BelongsTo::associate with unsaved Eloquent models

Created on 7 Nov 2017  路  8Comments  路  Source: laravel/framework

  • Laravel Version: 5.4.36
  • PHP Version: 7.1.2
  • Database Driver & Version: php-7.1-mysql, MySQL 5.7

Description:

I was trying to associate Eloquent model (unsaved) model with another (unsaved). After saving in database in table for first model no id of model from another table.
Seems like a bug.

Steps To Reproduce:

$people = new People();
$city = new City();

$people->city()->associate($city);

$city->save();
$people->save();

And... We have People without City.

Most helpful comment

Could we at least add a CantDoThatYetException (or perhaps a TransientOwnerException) so that uses of the associate() method (and perhaps other method) are made of aware of the logic error?

All 8 comments

IMO this is expected behavior. I wouldn't think you could create a relationship between 2 models that are not already represented in the database.

I believe at least one of the models must be saved in advance, in order to create the relationship.

@devcircus but we can access to related model before eloquent push ($people->city). Expected that $people->city and $city are same objects and when one of the models saved, another in moment of saving can access to key (id) of saved model.

Yeah i agree with @devcircus here, this looks like intended behaviour

You can't associate a row from a different table if that row doesn't exist. You don't have an ID (or what ever unique key) to associate until you save it.

$people = new People();
$city = new City(); 

$people->city()->associate($city); // People has no ID, can't associate yet.

$city->save(); // saved City so now city has ID but people still doesn't.
$people->save(); // Now people has ID, Suppose to insert relationship how now? 

@jekinney, think about OOP and read my previous comment. At the moment of saving second second model (People) we have ID of first model (City).

And one database query is better than 2 anyway (we need to save two models and then make BelongsTo::associate and save again).

Could we at least add a CantDoThatYetException (or perhaps a TransientOwnerException) so that uses of the associate() method (and perhaps other method) are made of aware of the logic error?

This is indeed the intended behavior for associate. If you want to propose a different way or add a new way to also persist relationships try to open up an issue at https://github.com/laravel/ideas

Was this page helpful?
0 / 5 - 0 ratings

Related issues

JamborJan picture JamborJan  路  3Comments

shopblocks picture shopblocks  路  3Comments

Anahkiasen picture Anahkiasen  路  3Comments

progmars picture progmars  路  3Comments

Fuzzyma picture Fuzzyma  路  3Comments