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.
$people = new People();
$city = new City();
$people->city()->associate($city);
$city->save();
$people->save();
And... We have People without City.
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
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?