menu

Questions & Answers

How insert an array of data in one query into the database

I have an array where each element contains data and an array. I save it in db with double foreach.

Сan i prepare an array of data and insert it in one request? I'm not confused much because my $user object in the $user->org_id field refers to the record I just inserted.

foreach ($xmlObject as $org)
        {
            $service = new PostService();
            $org1 = new Organization();
            $org1->name = $org->attributes()['Name'];
            $org1->save();
            
            foreach ($org as $item) {
                $user = new User();
                $user->first_name = $item->attributes()['firstname'];
                $user->last_name = $item->attributes()['lastname'];
                $user->org_id = $org1->id;
            }
        }

Organizations Shema

            $table->id()->autoIncrement();
            $table->string('name');
            $table->string('ogrn');
            $table->string('oktmo');
            $table->timestamps();

Users Shema

            $table->id()->autoIncrement();
            $table->string('first_name')->nullable(false);
            $table->string('last_name')->nullable(false);
            $table->bigInteger('org_id')->unsigned();
            $table->foreign('org_id')->references('id')->on('organizations');
            $table->timestamps();

xml Data

<orgs>
 <org Name="FFF Company">
  <user firstname="Sara" lastname="Freser" />
  <user firstname="Mary" lastname="Popins" />
 </org>
 <org Name="SweetDream">
  <user firstname="Vin" lastname="Diz"  />
 </org>
</orgs>
Comments:
2023-01-18 23:30:15
Please post your schema and sample data
2023-01-18 23:30:15
@RohitGupta yeah sorry ,it looks like this
2023-01-18 23:30:15
btw, you are reassigning $org immediately in the foreach loop and you are iterating $org which looks to be a Model instance, this will just iterate the public properties of the object
Answers(0) :