New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
希望增加一个whereIf的用法系列,这样就不用每次手动去判断了。 #473
Comments
不是有when方法么? |
我想要的跟when还不太一样,不需要跟when这么灵活,whereIf的用法,跟where相比,只是,第一个参数是布尔值,其余的参数跟where一样,只不过延后了一位。 比如:
用whereIf
其他的whereIn,whereNotIn等方法都这样,变成whereIfIn,whereIfNotIn。 |
<?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); |
看了 <?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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
增加之后,第一个参数是布尔值,这样代码就可以写成这个样子:
现在只能写成这个样子:
现在的写法,需要单独把模型的query实例化给一个变量,然后才能进行条件判断。
如果直接提供一个whereIf的用法,代码就很方便了,可以链式调用下来。
The text was updated successfully, but these errors were encountered: