Say I have two Models: User and Task
Their relationship is as follows: User can have many tasks (belongsToMany) Task can have many users (belongsToMany)
$user = new User();
$task = new Task();
Normally, I'd do something like this:
$user->tasks->attach($task)
But the problem is the User and Task is not persisted in the database. So if I run the last code above, I'll get an integrity constraint because these models have no id.
I have looked into the documentation and I found at that there is a method associate() but this requires either one of the model that has an id (saved in the database).
Is there any way I could attach a Model to another Model without them having persisted in the database?
I guess you could call setRelation manually.
$model->setRelation('child', $childInstance);
eLSE
You create a new model simply by instantiating it:
$model = new Model;
You can then save it to the database at a later stage:
$model->save();
You can use the make method on the relation itself to create a relation model instance without saving. The make method is not part of the docs but part of the Laravel API Docs.
Example:
$task = $user->tasks()->make($attributes);
If you would like to persist $task afterwads you can save the task with the save method.
$task->save();
Source:
make(array $attributes = [])
Create and return an un-saved instance of the related model.
https://laravel.com/api/11.x/Illuminate/Database/Eloquent/Relations/HasMany.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With