think-orm
think-orm copied to clipboard
希望增加一个whereIf的用法系列,这样就不用每次手动去判断了。
增加之后,第一个参数是布尔值,这样代码就可以写成这个样子:
$post_id = $this->request->param('post_id');
$list_visit = PostVisit::with(['post'])->order('id desc')
// 这一行
->whereIf(!empty($post_id),'post_id',$post_id)
->paginate([
'url' => 'Index/visit',
'list_rows' => 20,
'query' => [
'post_id' => $post_id,
],
]);
View::assign('list_visit', $list_visit);
现在只能写成这个样子:
$post_id = $this->request->param('post_id');
$model_list_visit = PostVisit::with(['post'])->order('id desc');
// 目前只能这么判断
if(!empty($post_id)) {
$model_list_visit->where('post_id', $post_id);
}
$list_visit = $model_list_visit->paginate([
'url' => 'Index/visit',
'list_rows' => 20,
'query' => [
'post_id' => $post_id,
],
]);
现在的写法,需要单独把模型的query实例化给一个变量,然后才能进行条件判断。 如果直接提供一个whereIf的用法,代码就很方便了,可以链式调用下来。
不是有when方法么?
我想要的跟when还不太一样,不需要跟when这么灵活,whereIf的用法,跟where相比,只是,第一个参数是布尔值,其余的参数跟where一样,只不过延后了一位。
比如:
if(!empty($id)){
$model->where('user_id',$id)
}
用whereIf
$model->whereIf(!empty($id),'user_id',$id);
其他的whereIn,whereNotIn等方法都这样,变成whereIfIn,whereIfNotIn。
when 已经足够了
<?php
$post_id = $this->request->param('post_id');
$list_visit = PostVisit::with(['post'])->order('id desc')
->when(!empty($post_id), fn ($query) => $query->where('post_id', $post_id))
->paginate([
'url' => 'Index/visit',
'list_rows' => 20,
'query' => [
'post_id' => $post_id,
],
]);
View::assign('list_visit', $list_visit);
看了 when 的代码,第二个参数还可以是数组
<?php
PostVisit::when(! empty($post_id), ['post_id' => $post_id]);
// or
PostVisit::when(! empty($post_id), ['post_id', '=', $post_id]);
箭头函数的写法倒是简单些。 可以再讨论讨论。
为什么一定要这样写?就不能:
$post_id = $this->request->param('post_id');
$map = [];
if (!empty($post_id)) {
$map[] = ['post_id', '=', post_id];
}
$list_visit = PostVisit::with(['post'])->where($map)->order('id desc')->paginate(['url' => 'Index/visit', 'list_rows' => 20, 'query' => ['post_id' => $post_id]]);
View::assign('list_visit', $list_visit);