0

I have two related tables: table A and table B.

model a

public function comments(){
    return $this->hasMany('App\tableB');
}

model b

public function posts()
{
    return $this->belongsTo('App\tableA');
}

I want create a record in table A, then use it and insert many records in table B.

This code works :

$s = tableA::create(["postname" =>"test"]); // this create success

now I insert records of comments for this created post:

$s->comments()->createMany([["txt"=>"a"],["txt"=>"b"]]);

Question 1 :

I enabled query debug and see this code :

$s->comments()->createMany([["txt"=>"a"],["txt"=>"b"]]);

runs a query for each insert (i.e. insert into x values (a) and insert into x values (b ) and ........) !!!

How can the code be changed such that it will not run one Insert statement for each record?!

Question 2 :

I have a problem with passing an array to the laravel createMany() method :(.

How can this output [["txt"=>"a"],["txt"=>"b"]] be created with php?

I tried to create with below code but its not working and laravel shows an error

  $b = array();
        array_push($b,"txt","yellow");
        array_push($b,"txt","ssss");

Can anybody help me?

i want Exactly this : see the link (The createMany Method ) --- but it run multi query for each insertion

$post = App\Post::find(1);

$post->comments()->createMany([
    [
        'message' => 'A new comment.',
    ],
    [
        'message' => 'Another new comment.',
    ],
]);
  • Possible duplicate of [Bulk Insertion in Laravel using eloquent ORM](https://stackoverflow.com/questions/12702812/bulk-insertion-in-laravel-using-eloquent-orm) – Kyslik Aug 13 '17 at 19:28
  • no this is normal insertion not relationship – ᴜɴᴅᴇғɪɴᴇᴅ Aug 14 '17 at 03:22
  • i want Exactly this : [https://laravel.com/docs/5.4/eloquent-relationships#inserting-and-updating-related-models](https://laravel.com/docs/5.4/eloquent-relationships#inserting-and-updating-related-models) (The createMany Method ) --- but it run multi query for each insertion :( how to fix this? – ᴜɴᴅᴇғɪɴᴇᴅ Aug 14 '17 at 03:52
  • It is by design that Laravel will do this... https://github.com/laravel/framework/blob/5.4/src/Illuminate/Database/Eloquent/Relations/HasOneOrMany.php#L264 – Aaron Fahey Aug 14 '17 at 04:06
  • YES i dont want edit laravel :D but i want Alternative way :( do u have any suggest ? – ᴜɴᴅᴇғɪɴᴇᴅ Aug 14 '17 at 04:10

0 Answers0