如果在 Where NOT IN 中传递变量,查询 laravel 不工作

query laravel not working if pass variable in Where NOT IN

我正在尝试从数据库中筛选项目 table 我所做的是获取我想要排除的 ID,然后通过 -> laravel 中的 whereNotIn,我传递 ids

$idcontracts=array();
$idbike=array();
$biciCorretta = array();

$findcontract=Contract::whereRaw('? between data_inizio and data_fine', [$datainizio])->whereRaw('? between data_inizio and data_fine', [$datafine])->get();
        foreach ($findcontract as $key) {
            if (!in_array($key->id,$idcontracts)) {
                array_push($idcontracts,$key->id);
            }
        }
        
        foreach ($idcontracts as $idcontract) {
            $bike_contracts=DB::table('bike_contract')->where('contract_id',$idcontract)->get();
            foreach ($bike_contracts as $bike_contract) {
                if (!in_array($bike_contract->bike_id,$idbike)) {
                    array_push($idbike,$bike_contract->bike_id);
                }
            }
            
            
        }
        
        $notid=implode("', '",$idbike);

到目前为止我没有问题。 “内爆”的结果给了我要删除的 ID

这是 $idbike 和 $notid 的结果:

这是我为排除找到的 ID 而编写的查询:

$bikes = Bike::with('category')->whereNotIn('id', [$notid])->orderBy('category_id')->get();

问题是它不排除我通过 $notid

传递的 ID

但如果我手动传递 ID,它会删除它们:

$bikes = Bike::with('category')->whereNotIn('id', [40,41,34,36,39])->orderBy('category_id')->get();

我是不是做错了什么?

你不应该内爆 $notid,这使它成为 string 并且 Laravels whereNotIn() 已经为你做到了。

->whereNotIn('id', $idbike)

并删除 $notid 参数,因为不需要它。

内爆将在字符串中 return,因此它无法正常工作,您应该将其作为数组传递。

如果打印数据

$idbike =[40,41,34,36,39];

print_r($idbike);

输出将是数组

Array
(
    [0] => 40
    [1] => 41
    [2] => 34
    [3] => 36
    [4] => 39
)

如果你打印下面的代码

$notid=[implode(",",$idbike)];
print_r($notid);

输出将是

Array
(
    [0] => 40,41,34,36,39
)

所以你的查询变成了

->whereNotIn('id', ["40,41,34,36,39"])

所以 laravel 正在搜索“40,41,34,36,39”的 ID。所以它没有返回结果

所以可以直接传数组给wherenotin

->whereNotIn('id', $idbike)

Laravel、whereNotIn 方法从集合中移除具有指定项值且包含在给定数组中的元素。这意味着你必须传递一个数组

所以,idbike就是你说的数组

$bikes = Bike::with('category')->whereNotIn('id', idbike)->orderBy('category_id')->get();