Home>

When registering to the auto_increment id column of table A, I want to register the same column name id in another table at the same time

Please write your question in detail here.
We practice DB operation by learning PHP (Laravel).
There is a column called user_id of auto_increment in table A, and I want to store the same number in the column with the same name as user_id in table B when I put data there.
I found that I can get id by using insertGetId when inserting data into table A, but I'm still troubled by checking how I can use it to reflect in table B.

Applicable source code
// Describe the following in the TableA model. Get the id with this (notation method that I searched Gugu)
$id = \ DB :: table ('table_A')->insertGetId ($data, 'user_id');
// TableB model is usually only insert
\ DB :: table ('table_B')->insert ($data);
// Unknown how to write to controller.
 public function create (Request $request) {
 $data ['user_id'] = $request->user_id;
 $data_id = \ App \ Models \ tableA :: insert ($data);
}
Changed from the above to the following with reference to the comments
Added the following to Model A
protected $primaryKey = 'user_id';
----------------------------------
Changed Controller to
$a = new \ App \ Models \ A ();
$a->save ();
$b = new \ App \ Models \ B ();
$b->user_id = $a->user_id;// $a's user_id is auto_increment
$b->save ();
The following error occurs after correction
Error description
SQLSTATE [23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails ~

I think there are a lot of deficiencies, but if you know a wide variety of notation, please professor.

Supplemental information (FW/tool version etc.)

OS: Mac (catalina10.15.1)
PHP: ver7.3
Laravel: ver5.8
Mysql: ver5.7

  • Answer # 1

      

    I understand that I can get id by using insertGetId when inserting data into table A, but I'm still troubled by checking how I can use it to reflect in table B .

    For Laravel, use Eloquent (model)
    The id when saved is automatically set to the id of the instance.

    So if you write simply, it is the following procedure.

    $a = new \ App \ Models \ A ();
    $a->save ();
    $b = new \ App \ Models \ B ();
    $b->id = $a->id;
    $b->save ();

    If you really want to use the column name user_id instead of id
    Set $​​primaryKey property to model A and make any column the primary key

  • Answer # 2

    Is it possible to process with trigger?
    Not only when inserting but also what you want to do when deleting or updating (changing to another number)
    I think it ’s better to consider