Laravel 条件数组 in 的用法

需要将使用in查询的字段写成闭包的形式

$where['status'] = 1;
$ids = [1,2];
$where[] = [function($query) use ($ids){
    $query->whereIn('id', $ids);
}];
$list = User::where($where)
    ->get();

生成sql如下

select * from `users` where (`status` = 1 and (`id` in (1, 2)))
本作品采用《CC 协议》,转载必须注明作者和本文链接
镜花水月
Image
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 6

试了下,可以省去 'id' =>

6年前 评论
Image st-lyt (楼主) 6年前

User::where('status',1)->whereIn('id',[1,2,3,4,5])->get();
为什么搞那么复杂?

6年前 评论
Image st-lyt (楼主) 6年前

还有这种写法不错!我使用的这种 $where[] = ['in'=>['tn_user_base.id'=>$medical_number_ids]];

6年前 评论
Image st-lyt (楼主) 6年前
Image J_Wang 4年前

我一般直接使用 when()

6年前 评论
Jourdon

使用 when 比较好理解,使闭包看着好怪。

$status = 1;
$ids = [1,2];
User::when($status, function ($query, $status) {
        return $query->where('status', $status);
    })
        ->when($ids, function ($query, $ids) {
            return $query->whereIn('id', $ids);
        })
        ->get();
6年前 评论
Image st-lyt (楼主) 6年前
Image 小手冰凉 5年前

问下,whereIn('字段',数组) 这数组的长度是否有限呢? 或者说$ids 过长怎么优化处理呢?

5年前 评论
Image ouer1994 5年前
Image 残夜 5年前
Image ouer1994 5年前
Image 残夜 5年前
Image ouer1994 5年前
Image 残夜 5年前
Image ouer1994 5年前
Image 残夜 5年前
Image ouer1994 5年前
Image 残夜 5年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!