I need to insert data into one table and references data into another table in ZF2 using tableGateway.
For example, when I am registering a user, I have to insert user data into one table and this user hobbies data(Multiple rows) into another table with the references of the inserted user id and Update data also should work.
I have referred this url: Want to insert into two tables using one form in ZF2
But this won’t help me.
Advertisement
Answer
Suppose we are in ‘user’ model. So by default tableGateway will insert data in user table and for hobbies table, I have instansiated new tableGateway as ‘$userTable’.
$data = array( 'id' => $user->id, 'name' => $user->name, ); $this->tableGateway->insert($data); //this will insert data in user table $last_id=$this->tableGateway->lastInsertValue; //getting last inserted id $adapter=$this->tableGateway->getAdapter(); $userTable = new TableGateway('hobbies', $adapter); //this will insert in hobbies table. $data_arr = array( 'link_id' => $last_id, 'music_info' =>'test', ); $artistTable->insert($data_arr);