tp5.1 whereTime whereRaw 原数据中达不到查询条件 可以改变查询条件(比如在原数据时间字段上延迟多30分中 ...

论坛 期权论坛 脚本     
匿名技术用户   2020-12-30 08:15   448   0

例子:查询endtime字段时间结束后30分钟的数据

表中值是:endtime = 2019-11-22 11:00:00;

->whereTime('endtime', '>=', time())

但是因为延迟30分钟,上面查询条件的数据就不对,查不到延迟后的数据,因为表中数据就是30分前的。

所以修改查询语句,语句中应该是要查询30分钟后的

->whereRaw('unix_timestamp(endtime) + defer_time * 60 >='.time())

1.unix_timestamp(endtime) + defer_time * 60 说明:先把endtime转成时间戳,然后再加延迟的时间

2.defer_time * 60 分钟转为秒

3.加时间再与当时时间作判断

unix_timestamp()=MySQL时间戳与日期格式的相互转换

unix_timestamp()参考:https://www.cnblogs.com/bluealine/p/9007439.html

defer_time=30;就是要延迟多少分钟

endtime=结束时间

TP5.1教程:https://www.kancloud.cn/manual/thinkphp5_1/354030

实例代码:

     //待上课表 
            $list2=Db::name('live_course')
            ->field('id,pid,title,starttime,classhour,endtime,bigclass,state,advance_time,defer_time')
       ->withAttr('realendtime', function($value, $data) {
        //defer_time延迟时间:让学延迟多少分钟还能观看进入直播,
        $target_time = strtotime($data['endtime']) + ($data['defer_time'] * 60);
        $value=date("Y-m-d H:i:s",$target_time); 
       return $value;
      })
            ->whereIn('id',$allpid_future_ccid_all)
            ->where('deleted',0)
            ->where('state',0)//状态 0=启用 1=直播结束(就算直播服务器没有结束,用户界面都会显示直播结束)
            //->whereTime('endtime', '>=', time())
            ->whereRaw('unix_timestamp(endtime) + defer_time * 60 >='.time())
            ->order('starttime', 'asc')
            ->select();
SQL语句:
string(286) "SELECT `id`,`pid`,`title`,`starttime`,`classhour`,`endtime`,`bigclass`,`state`,`advance_time`,`defer_time` FROM `edu_live_course` WHERE  `id` IN (51,52,85,80,82)  AND `deleted` = 0  AND `state` = 0  AND ( unix_timestamp(endtime) + defer_time * 60 >=1574395675 ) ORDER BY `starttime` ASC"

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:7942463
帖子:1588486
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP