gpt4 book ai didi

php - 如何像 SQL 中的括号一样用 eloquent 编写查询?

转载 作者:行者123 更新时间:2023-11-29 13:08:34 25 4
gpt4 key购买 nike

我有一个查询,其中所有参数都是可选的 我想在以下情况下选择行:“选择所有具有 marketplace_id 或 account_id 并具有标题的产品”。换个说法

 select * from produts where (marketplace_id in (...) or account_id in (...)) and title ilike "blah".

这是我能到达的最远距离。

   $query = Product::query();

if($parametros_pesquisa['marketplaces'] !== null )
{

$query->whereIn('marketplace_id', $search_parameters['marketplaces']);

}if($parametros_pesquisa['contas'] !== null){

$query->orWhereIn('conta_id', $search_parameters['account']);

} if($search_parameters['titulo'] !== null){

$query->where("titulo", 'ilike', '%' . $search_parameters['titulo'] . '%');


}

此处,$search_parameters['marketplaces']$search_parameters['account'] 将是一个 ID 数组 [1, 2, 3]。我检查用户是否指定了搜索条件并将其动态包含在查询中。看起来查询正在执行,就像查询中的括号不存在一样。我怎样才能达到我想要的?

最佳答案

您可以将回调传递到 where 以对 进行分组。

//quick example of Parameter Grouping:

$query = Product::query();

$query->where(function ($query) use ($search_parameters){
$query->whereIn('marketplace_id', $search_parameters['marketplaces'])->orWhereIn('conta_id', $search_parameters['account']);
})->where("titulo", 'ilike', '%' . $search_parameters['titulo'] . '%');

请阅读 Laravel 数据库查询生成器:DOCS

关于php - 如何像 SQL 中的括号一样用 eloquent 编写查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57929398/

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