如何将插入的查询 ID 用于 运行 中的另一个查询 Laravel

How to use inserted query id for running another query in Laravel

我想像这样插入一些数据:

foreach($data as $arr){
    $query=DB::table('users');
    $query->insert([
          'usr_name' => $arr['mbr_mobile'],
          'created_at' => now()->toDateTimeString(),
          'updated_at' => now()->toDateTimeString(),
    ]);
    DB::table('members')->insert([
          'mbr_mobile' => $arr['mbr_mobile'],
          'mbr_usr_id' => $query['id'], // returns error
          'created_at' => now()->toDateTimeString(),
          'updated_at' => now()->toDateTimeString(),
    ]);
}

如您所见,我尝试将数据插入 users table,然后将数据插入 members table.

但我确实需要数据刚刚插入 users table 的行的 id,所以我可以将它用于 mbr_usr_id

但这是错误的,因为它显示 无法将类型 Illuminate\Database\Query\Builder 的对象用作数组 错误。

如果我写 $query->id 而不是 $query['usr_id'],我会得到 Undefined 属性 错误!

那么我怎样才能将插入的查询 ID 用于 运行 中的另一个 INSERT 查询?Laravel?


更新#1:

如果我这样做,我会得到 Call to a member function lastInsertId() on bool 错误:

$lastInsertedID = $query->insert([
       'usr_name' => $arr['mbr_mobile'],
       'usr_is_active' => 1,
       'usr_password' => bcrypt($arr['mbr_national_code']),
       'created_at' => now()->toDateTimeString(),
       'updated_at' => now()->toDateTimeString(),
])->lastInsertId();

DB::table('members')->insert([
       ...
       'mbr_usr_id' => $lastInsertedID,
]);

使用 insertGetId 代替 insert。 或者用Inserting & Updating via Models,有个idgetter

使用这个insertGetId 这是如何使用它的示例

$id = DB::table('users')
->insertGetId(
[
    'usr_name' => $arr['mbr_mobile'],
    'created_at' => now()->toDateTimeString(),
    'updated_at' => now()->toDateTimeString(),
]);

请试试这个

foreach($data as $arr){
    $user_id = DB::table('users')->insertGetId([
          'usr_name' => $arr['mbr_mobile'],
          'created_at' => now()->toDateTimeString(),
          'updated_at' => now()->toDateTimeString(),
    ]);
    DB::table('members')->insert([
          'mbr_mobile' => $arr['mbr_mobile'],
          'mbr_usr_id' => $user_id, 
          'created_at' => now()->toDateTimeString(),
          'updated_at' => now()->toDateTimeString(),
    ]);
}