M
M
MarkBogrov2017-07-08 13:17:48
Laravel
MarkBogrov, 2017-07-08 13:17:48

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

2 answer(s)
A
Andrey Novikov, 2017-07-10
@MarkBogrov

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);
    }

And then, after creating the entity element, you work through these relays:
$node = Node::create([
    'title' => 'foobar',
    'etc' => '123'
]);
$node->events()->create([
    'title' => 'foobar',
    'etc' => '123'
]);
$node->places()->create([
    'title' => 'foobar',
    'etc' => '123'
]);

Or like this:
Node::create([
    'title' => 'foobar',
    'etc' => '123'
])->events()->create([
    'title' => 'foobar',
    'etc' => '123'
]);

A
Alexander Talalaev, 2017-07-08
@neuotq

$node = new Node;
$node->blahblah = $blahblah;
$node->save();

After saving, you can apply $node->idand there will be happiness.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question