Support the ongoing development of Laravel.io →
posted 9 years ago
Eloquent

I have three models that are something like Grid, GridItem, and Item. Grid has pages, rows, and cols. GridItem has grid_id, item_id, page, row, and col. Item is a list of predefined objects.

I need to be able to mass-create GridItems when Grid is created. I already have an event listener set up to listen for the proper event. So far, I'm running a for loop with pages, rows, and cols with the last loop being where I create my GridItem model with only page, row, and col listed:

public function handle(Grid $grid)
{
    for ($page=0; $page < $grid->pages; $page++) { 
        for ($row=0; $row < $grid->rows; $row++) { 
            for ($col=0; $col < $grid->cols; $col++) { 
                GridItem::create(['col' => $col, 'row' => $row, 'page' => $page])
                    ->item()->associate(Item::find(1))
                    ->grid()->associate($grid);
            }
        }
    }
}

I have also tried using Grid and Item::find(1) first and associating/saving from there, but they all fail with foreign key constraint errors.

How do I associate/save two relationships at once?

Last updated 3 years ago.
0

Sign in to participate in this thread!

PHPverse

Your banner here too?

mseymour mseymour Joined 25 Feb 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.