Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

skeith22's avatar
Level 22

ORM how to automatically append/save the id of the parent related to it but it's 2 steps away

Has anyone tried to save a relationship id where you need the of id (model1) AND the id (model2) of model1 to the data being saved.

basically it's this.

Model1 (hasManyThrough Model3->Model2) // 1st Model
id

Model2 (belongsTo Model1, hasMany Model3) // 2nd Model
id

Model3 (belongsTo Model2, belongsTo Model1) // 3rd Model
id (Model 3 primary key)
model2_id (Model 2 foreign key)
model1_id (Model 1 foreign key) << I NEED to automatically be set also using just relationship

$model2->model3()->createMany([])

it only inserts the model2_id automatically, how do I automatically get model1_id as well just using relationship?

I was wondering if Eloquent could handle it like this

$createdModel2 = $model2->create();
$createdModel2->model1()->model3()->createMany([])

Then again this one will only have the model1_id and NOT the model2_id anymore, I was hoping it would have both model1_id AND model2_id on model3

0 likes
2 replies
LaryAI's avatar
Level 58

To automatically append and save the model1_id when creating Model2Items through a relationship, you can leverage Eloquent's model events or use a custom method to handle the creation process. Here's a solution using a custom method:

First, ensure your models are set up correctly with the necessary relationships:

Next, create a custom method in Model2 to handle the creation of Model2Items and automatically set the model1_id:

class Model2 extends Model
{
    // Existing relationships...

    public function createModel2ItemsWithModel1Id(array $items)
    {
        $model1Id = $this->model1_id; // Assuming model1_id is a foreign key in Model2

        foreach ($items as &$item) {
            $item['model1_id'] = $model1Id;
        }

        return $this->model2Items()->createMany($items);
    }
}

Now, you can use this method to create Model2Items with both model2_id and model1_id automatically populated:

$model2 = Model2::find($someModel2Id);
$model2->createModel2ItemsWithModel1Id([
    ['attribute1' => 'value1', 'attribute2' => 'value2'],
    ['attribute1' => 'value3', 'attribute2' => 'value4'],
]);

This approach ensures that each Model2Items instance is created with the correct model1_id and model2_id without manually setting model1_id each time.

Please or to participate in this conversation.