我想插入一些這樣的資料:
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表中,然后將資料插入members表中。
但是我確實需要id資料剛剛插入users表中的行的 ,因此我可以將它用于mbr_usr_id.
但這是錯誤的,因為它顯示我不能使用 Illuminate\Database\Query\Builder 型別的物件作為陣列錯誤。
如果我寫$query->id而不是$query['usr_id'],我會收到未定義的屬性錯誤!
那么如何使用插入的查詢 ID在 Laravel 中運行另一個INSERT查詢呢?
更新#1:
如果我這樣做,我會在 bool錯誤時呼叫成員函式 lastInsertId():
$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,
]);
uj5u.com熱心網友回復:
請試試這個
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(),
]);
}
uj5u.com熱心網友回復:
使用insertGetId
這里是如何使用它的示例
$id = DB::table('users')
->insertGetId(
[
'usr_name' => $arr['mbr_mobile'],
'created_at' => now()->toDateTimeString(),
'updated_at' => now()->toDateTimeString(),
]);
uj5u.com熱心網友回復:
使用insertGetId代替insert。或者使用Inserting & Updating via Models,有一個 id getter
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/394578.html
標籤:php 拉拉维尔 laravel-5.8
上一篇:如何格式化關系日期?
