laravel 实现根据字段不同值做不同查询

时间:2022-07-27
本文章向大家介绍laravel 实现根据字段不同值做不同查询,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

在开发过程中我们经常遇到这种情况:

例如,一个信息表message,字段type 1.操作提醒 2.平台通知,表message_read记录当信息是平台通知时用户浏览状况

那么 当信息是平台通知时是针对的所有用户,我们想根据他是否浏览状态去在消息提醒里去显示他未读的消息

语句如下(laravel)

public function index()
 {
//  监听sql语句
//  DB::listen(function($query) {
//   $bindings = $query- bindings;
//   $sql = $query- sql;
//   foreach ($bindings as $replace){
//    $value = is_numeric($replace) ? $replace : "'".$replace."'";
//    $sql = preg_replace('/?/', $value, $sql, 1);
//   }
//   dd($sql);
//  });
   $uid = 13; 
   return MessageModel::where(function($query) use($uid){
    $query- where(['type'= 2,'status'= 1,])- whereNotIn('id',function($query) use($uid){
     $query- select('mid')- from('message_read')- where([['message.id','=',DB::raw('mid')],'uid'= $uid]);
    });
   })- orwhere(function($query) use($uid){
    $query- where(['type'= 1,'status'= 1,'is_read'= 2,'uid'= $uid]);
   })- get();
 }

数据表格式

CREATE TABLE `message` (
 `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
 `uid` int(11) DEFAULT NULL COMMENT '需要通知的用户id',
 `title` varchar(255) NOT NULL COMMENT '标题',
 `describe` varchar(255) DEFAULT NULL COMMENT '简介',
 `type` tinyint(4) DEFAULT NULL COMMENT '通知类型 1.行为通知 2.平台通知',
 `is_read` tinyint(4) DEFAULT NULL COMMENT '是否已读 1.已读 2.未读',
 `status` tinyint(4) DEFAULT '1' COMMENT '1存在 2删除',
 `created_at` int(11) DEFAULT NULL,
 `updated_at` int(11) DEFAULT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4 COMMENT='消息表';


CREATE TABLE `message_read` (
 `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
 `uid` int(11) DEFAULT NULL COMMENT '用户id',
 `mid` int(11) DEFAULT NULL COMMENT '消息id',
 `created_at` int(11) DEFAULT NULL,
 `updated_at` int(11) DEFAULT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COMMENT='平台消息通知阅读记录表';

以上这篇laravel 实现根据字段不同值做不同查询就是小编分享给大家的全部内容了,希望能给大家一个参考。