Php 基于数组中的记录创建多行-laravel
我有一个查询,它返回一个用户ID数组,每个用户都将从中得到通知Php 基于数组中的记录创建多行-laravel,php,laravel,Php,Laravel,我有一个查询,它返回一个用户ID数组,每个用户都将从中得到通知 $pstusrmembs = DB::table('postusrs') ->where('post_id', $post_id) ->where('accepted', 1) ->pluck('user_id'); 我需要在下面的“插入”代码中将每个用户id放在不同的行中: 如何更改$noti
$pstusrmembs = DB::table('postusrs')
->where('post_id', $post_id)
->where('accepted', 1)
->pluck('user_id');
我需要在下面的“插入”代码中将每个用户id放在不同的行中:
如何更改$notifs->rec\u uid=$pstusrembs编码>执行此操作?为此使用for循环:
foreach($pstusrmembs as $userID){
$notifs = new Notif();
$notifs->rec_uid = $userID;
$notifs->title = $post_title;
$notifs->save();
}
如果使用质量分配概念
如果您使用的是质量分配概念,而没有任何模型
事件或听众
我建议使用DB transaction来保持数据库的一致性,即使在系统出现故障的情况下也是如此,并将该列表准备为数组并插入一行中
$prepare = [];
foreach($pstusrmembs as $p) {
$prepare[] = [
'rec_id' => $p,
'title' => $post_title
];
}
DB::beginTransaction();
try {
Notif::insert($prepare);
DB::commit();
} catch (Exception $e) {
DB::rollback();
}
因此,您希望在rec\u uid
列中存储一个ID数组?json对数组数据进行编码并保存data@TharakaDilshan,我需要将每个id放在一行中(而不是一列中的id数组),其中每行都有相同的$post_标题。@AbdallahSakre For loop,我添加了答案,请看一看
foreach ($pstusrmembs as $userID) {
Notif::create(['rec_uid' => $userID, 'title' => $post_title]);
}
foreach ($pstusrmembs as $userID) {
$arrayOfNotif[] = ['rec_uid' => $userID, 'title' => $post_title];
}
Notif::insert($arrayOfNotif);
$prepare = [];
foreach($pstusrmembs as $p) {
$prepare[] = [
'rec_id' => $p,
'title' => $post_title
];
}
DB::beginTransaction();
try {
Notif::insert($prepare);
DB::commit();
} catch (Exception $e) {
DB::rollback();
}