PHP 这种查询怎么能写的好看点,优雅点,高级点呢

2022-10-26 22:39:27 +08:00
 tlerbao

代码如下(这是 thinkphp 写的):

return $this->alias('cus')
                ->join('admin a', 'cus.userID = a.id')
                ->field('cus.userID,a.cjName,count(*) AS count')
                ->when($month, function ($query) use ($month) {
                    $query->whereMonth('cjTime', $month);
                },function ($query) {
                    $query->whereYear('cjTime', date('Y'));
                })
                ->when($brand_id, function ($query) use ($brand_id) {
                    $query->where('cus.cjbrandID', $brand_id);
                })
                ->when($shop_id, function ($query) use ($shop_id) {
                    $query->where('cus.cjMenDian', $shop_id);
                })
                ->group('cus.userID')
                ->order('count desc')
                ->limit(10)
                ->select()->each(function ($item) {
                    // ....
                    return $item;
                })->toArray();
983 次点击
所在节点    问与答
10 条回复
westoy
2022-10-26 23:34:35 +08:00
封装进函数

看不见的就是优雅的
qinrui
2022-10-26 23:38:17 +08:00
我用 medoo 查数据库,配合 smarty 模版引擎

不会用 thinkphp 等框架
sarices
2022-10-26 23:49:16 +08:00
直接在 MySQL 中建视图
baobao1270
2022-10-27 06:19:44 +08:00
TP 已经比手写 SQL 好很多了
不爽上 ORM
Rache1
2022-10-27 10:09:08 +08:00
添加 scope ,tp 里面叫搜索器,,把这些 when 操作放到里面去处理,后期改起来也方便一些,代码看上去就会简洁很多了。

如果使用 PHP 7.4 及以上,你的代码可以更加简单一些。

->when($brand_id, fn ($query) => $query->where('cus.cjbrandID', $brand_id))
->when($shop_id, fn ($query) => $query->where('cus.cjMenDian', $shop_id))
Rache1
2022-10-27 10:11:18 +08:00
另外,不要把所有东西都揉到一起,应该分开来出来。比如你后面的 each ,如果是我,就会单独弄一个方法去做。
xiaomada
2022-10-27 10:18:34 +08:00
scope+放弃全链接式调用
xiaomada
2022-10-27 10:24:07 +08:00
```
$query = $this->alias('cus')->join('admin a', 'cus.userID = a.id');

//条件 A
$query->when($month, function ($query) use ($month) {
$query->whereMonth('cjTime', $month);
},function ($query) {
$query->whereYear('cjTime', date('Y'));
});

//条件 B
$query->when($brand_id, function ($query) use ($brand_id) {
$query->where('cus.cjbrandID', $brand_id);
});

//条件 C
$query->when($shop_id, function ($query) use ($shop_id) {
$query->where('cus.cjMenDian', $shop_id);
});

//条件可以封装 scope
$query->onlyshop($shop_id);

//执行查询
$models = $query->group('cus.userID')
->field('cus.userID,a.cjName,count(*) AS count')
->order('count desc')
->limit(10);

//结果集处理
$models->each(function ($item) {
// ....
return $item;
});

return $models;
```
tlerbao
2022-10-27 20:50:55 +08:00
感谢楼上各位,还有没有大神指教
tlerbao
2022-10-27 20:51:18 +08:00
@westoy 其实现在我只要不进模型,不该这部分代码,还是心静自然凉的哈哈。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/890180

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX