Reputation: 47
I have model Object with relationship:
public function category(){
return $this->hasOne('App\FieldCategoriesValues');
}
How to add new value to category?
I tried:
$object = new Object();
$object->category()->save(["id" => 4])
It does not work.
Upvotes: 0
Views: 38
Reputation: 6345
In order to save the relationship the first model needs to be created before creating/saving the second model. You can check for existence of a mode with the $exists
attribute.
Also, you pass a model to a relationship's save()
method and an array to create()
.
For example for the parent model:
$object = new Object;
$object->exists; // false
$object->save();
$object->exists; // true
OR
$object = Object::create();
$object->exists; // true
Then you can save the related model as:
$category = new Category(["id" => 4]);
$object->category()->save($category);
OR
$category = $object->category()->create(["id" => 4]);
Upvotes: 1