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.',
],
]);