gpt4 book ai didi

laravel - 在 Laravel 查询生成器中使用变量(for 循环)

转载 作者:行者123 更新时间:2023-12-02 17:05:25 25 4
gpt4 key购买 nike

我有一个查询需要检查多个 orWhere 语句。

$cases = ['john', 'kate', 'mike', 'rob', 'josh', 'moe']

在这种情况下,我想使用 where 作为 for 循环。

Cat::where(function($q) use ($cases) {
$q->where('name', 'john')->orWhere('name', 'kate'); // etc
})->get();

是否有更简洁的方法将它与 for 循环一起使用,以便它在运行时链接 orWhere

最佳答案

您可以使用此代码

Cat::whereIn('name', $cases);

如果你不会,你也可以使用这个代码

Cat::where(function($q) use ($cases) {
$firstCase = array_shift($cases);
$q->where('name', $firstCase);
foreach($cases as $case) {
$q->orWhere('name', $case);
}
// other conditions this
})->get();

关于laravel - 在 Laravel 查询生成器中使用变量(for 循环),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51994109/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com