ThinkPHP的find查询必须加where等筛选条件才会执行

发布时间:2024-03-30浏览次数:125 次
简答记录下,在thinkphp中,如果通过模型,直接find或findOrEmpty查询数据,如果不加where等筛选条件,则不会执行,也就是会返回null,隐

简答记录下,在thinkphp中,如果通过模型,直接find或findOrEmpty查询数据,如果不加where等筛选条件,则不会执行,也就是会返回null,隐约记得之前5的版本的时候好像不加筛选条件的话,默认会按照主键排序的方式进行查询的。

即:

$res = $model->find(); // null
$res = $model->field('id')->find(); // null

这样的查询语句都是不会执行的,在调试器中时看不到相关sql语句的。

如果改成:

$res = $model->where('id', '>', 0)->find();

这种形式,则可以正常查询。通过查询文档,也没有发现官方文档中对这部分有说明。只是在delete删除中,有捎带提到delete删除时需要加条件的问题:

发现这个问题,是我在查询表中数据的条数时发现,用select有效,但是用find无效。

即:

// null
$res = $model->field('count(id) as total,sum(status = 0) as wait, sum(status = 1) as ok')->find(); 
// 有值
$res = $model->field('count(id) as total,sum(status = 0) as wait, sum(status = 1) as ok')->select(); 
// 有值
$res = $model->where('id', '>', 0)->field('count(id) as total,sum(status = 0) as wait, sum(status = 1) as ok')->find();

以上,简单记录一下,避免下次再掉坑。

标签:
扫一扫,在手机上查看