Answer the question
In order to leave comments, you need to log in
Laravel how to create related records at model save time?
Please tell me the answer to a banal question that for some reason I can not google. How to create other entities associated with it at the time of entity creation.
Available:
For example, I have a main Node model that stores the main fields for each entity on the site, such as Id, title, created_at, updated_at etc...
Then, for each entity type, there is its own table + model with a set of fields for this entity. Suppose there are two additional entities Events and Places.
Question:
How to get its Id at the time of saving the Node and write the values of the fields of the related entity with the id of the Node's head entity? How is it generally done? After all, one entity in flexible projects is never equal to one table in the database, and at the time of creation, the future id is usually still unknown
Thank you for any kicks in the direction of understanding.
Answer the question
In order to leave comments, you need to log in
In the Model Node, create relationships to Events and Places:
/**
* Relations to Events
*
* @return HasMany
*/
public function events() : HasMany
{
return $this->hasMany(Events::class);
}
/**
* Relations to Places
*
* @return HasMany
*/
public function places() : HasMany
{
return $this->hasMany(Places::class);
}
$node = Node::create([
'title' => 'foobar',
'etc' => '123'
]);
$node->events()->create([
'title' => 'foobar',
'etc' => '123'
]);
$node->places()->create([
'title' => 'foobar',
'etc' => '123'
]);
Node::create([
'title' => 'foobar',
'etc' => '123'
])->events()->create([
'title' => 'foobar',
'etc' => '123'
]);
$node = new Node;
$node->blahblah = $blahblah;
$node->save();
$node->id
and there will be happiness.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question