为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
慕容708150 2021-11-05 14:48:03
我有以下查询返回一组 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;该如何改变才能做到这一点?
查看完整描述

2 回答

?
holdtom

TA贡献1805条经验 获得超10个赞

为此使用 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);


查看完整回答
反对 回复 2021-11-05
?
神不在的星期二

TA贡献1963条经验 获得超6个赞

我会建议使用 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();

}


查看完整回答
反对 回复 2021-11-05
  • 2 回答
  • 0 关注
  • 148 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信