基于数组中的记录创建多行 - laravel

我有以下查询返回一组 user_ids,每个用户都会收到通知。


$pstusrmembs = DB::table('postusrs')

                    ->where('post_id', $post_id)

                    ->where('accepted', 1)

                    ->pluck('user_id');

我需要将每个 user_id 放在下面“插入”代码的不同行中:


                      $notifs = new Notif();

                      $notifs->rec_uid = $pstusrmembs;

                      $notifs->title = $post_title;

                      $notifs->save();

我$notifs->rec_uid = $pstusrmembs;该如何改变才能做到这一点?


慕容708150
浏览 149回答 2
2回答

holdtom

为此使用 for 循环:foreach($pstusrmembs as $userID){        $notifs = new Notif();        $notifs->rec_uid = $userID;        $notifs->title = $post_title;        $notifs->save();}如果您正在使用批量分配概念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);

神不在的星期二

我会建议使用 DB 事务来保持数据库一致,即使在系统故障的情况下,并将该列表准备为数组并插入一行......$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();}
打开App,查看更多内容
随时随地看视频慕课网APP