gpt4 book ai didi

php - 如何在 Laravel 5.5 中进行多次插入?

转载 作者:行者123 更新时间:2023-12-01 09:42:10 27 4
gpt4 key购买 nike

我想在我的 Laravel 项目中进行多次插入,但我不知道该怎么做。我需要循环它还是有任何其他方法可以做到这一点?我有点困惑。我正在使用查询生成器。

Controller 代码。

if($request->smsn == 'on'){
$events->smsnotify = 1;

$numbers = \DB::table('users')
->where('school_id', '=', $sid->school_id)
->where('role', '=', $request->group_id)
->select('phone','name')
->get();

dd($numbers);


$sms = DB::table('sms')->insert([
'user_id' => $sid->id,
'school_id' => $sid->school_id,
'msg' => 'New Event '. $request->name,
'mobile_number' => $numbers,
'name' => 'Sample',
'isSend' => 1
]);



}

转储结果

Collection {#552 ▼
#items: array:5 [▼
0 => {#550 ▼
+"phone": "+63 (928) 206-5706"
+"name": "Ayden Kutch"
}
1 => {#568 ▼
+"phone": "(0817) 447-1492"
+"name": "Ruthie Quigley"
}
2 => {#567 ▼
+"phone": "+63 (920) 203-3874"
+"name": "Alaina O'Kon"
}
3 => {#569 ▶}
4 => {#570 ▶}
]
}

我想像这样把它插入到我的sms表中

+----+---------+---------------+---------------+--------+------------+------------+-----------+-------------+
| id | user_id | msg | mobile_number | isSend | created_at | updated_at | school_id | name |
+----+---------+---------------+---------------+--------+------------+------------+-----------+-------------+
| 8 | 13 | New Event | 123456 | 1 | NULL | NULL | 2 | Ayden Kutch |
+----+---------+---------------+---------------+--------+------------+------------+-----------+-------------+

在每个名字和数字中。它会生成另一行。

最佳答案

您可以在一个循环中执行多个插入查询,或对一个或多个数组执行单个插入查询,但您需要先构建该数组。

$data = [];

foreach ($numbers as $number) {
$data[] = [
'user_id' => $sid->id,
'school_id' => $sid->school_id,
'msg' => 'New Event',
'mobile_number' => $number->phone,
'name' => $number->name,
'isSend' => 1
];
}

DB::table('sms')->insert($data);

这会构建一个包含多个记录的数组,以便一起插入。

"You may even insert several records into the table with a single call to insert by passing an array of arrays. Each array represents a row to be inserted into the table"

Laravel 5.5 Docs - Query Builder - Inserts

关于php - 如何在 Laravel 5.5 中进行多次插入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58925632/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com