Laravel 查询中的循环未定义偏移错误

For loop undefined offset error in Laravel query

我正在尝试包含 for loop 以将 where 条件添加到我的查询中,但它在 $ProductSubCategory 上返回 undefined offset 1 错误。 $ProductSubCategory 的内容是我想作为条件包含的字符串数组。

$Product = Product::select('id','ProductWorkpiece','ProductCategory','ProductName','ProductImage','ProductSubCategory')
    ->where('Status','=','1')
    ->Where(function ($query) use ($ProductSubCategory) {
        for ($i=1; $i <= $ProductSubCategory ; $i++) { 
            $Product->where('ProductSubCategory', '=', $ProductSubCategory[$i]);
        }
    })->get();

https://pastebin.com/uDSywsQv(Laravel 查询生成器代码段)

这是我想使用 Laravel 的查询生成器复制的 MySQL 查询,我将如何执行此操作?

SELECT 
    `id`,
    `ProductWorkpiece`,
    `ProductCategory`,
    `ProductName`,
    `ProductImage`,
    `ProductSubCategory`
FROM
    `Product`
WHERE 
    `ProductSubCategory` = 'Laser Marking Machine' OR 
    `ProductSubCategory` = 'Dot Marking Machine' OR 
    `ProductSubCategory` = 'Digital Microscope' AND 
    `Status` = '1'

https://pastebin.com/AMWCz32g(所需的 MySQL 片段)

看这个$ProductSubCategory不是数组或者没有1的索引。根据 $ProductSubCategory 的内容,您可以使用几种方法。

解决方案 1:$ProductSubCategory 是一个字符串数组

$Product = Product::select('id','ProductWorkpiece','ProductCategory','ProductName','ProductImage','ProductSubCategory')
    ->where('Status','=','1')
    ->whereIn('ProductSubCategory', $ProductSubCategory)
    ->get();

这里可以使用whereIn()指定字符串数组,无需循环。

解决方案 2.1:$ProductSubCategory 是记录的对象集合

$Product = Product::select('id','ProductWorkpiece','ProductCategory','ProductName','ProductImage','ProductSubCategory')
    ->where('Status','=','1')
    ->where(function ($query) use ($ProductSubCategory) {
        foreach($ProductSubCategory as $subcategory) {
            $query->orWhere('ProductSubCategory', '=', $subcategory->name);
        }
    })->get();

这里我们使用 foreach 遍历每个对象记录,然后使用 orWhere 而不是 WHERE foo = bar AND foo = bar2 AND foo = bar3

从该对象引用 name 字段

$subcategory->name 用作占位符,使用适合您的字段名称。

注意 在你的版本中你做了 function($query) 但随后引用 $Product 而不是 $query 来做你的 where 子句。

编辑/更新

解决方案 2.2:$ProductSubCategory 是记录的对象集合

$subCategories = $ProductSubCategory->only('name')->toArray();
$Product = Product::select('id','ProductWorkpiece','ProductCategory','ProductName','ProductImage','ProductSubCategory')
        ->where('Status','=','1')
        ->whereIn('ProductSubCategory', $subCategories)
        ->get();

这与解决方案 1 相同,只是我们使用收集方法 only() 仅检索 name 字段(相应地更改)然后转换名称 toArray() 所以它可以用作 whereIn 条件的一部分。 这在我这边未经测试,但理论上应该可行

了解 $ProductSubCategory 的内容和类型会更有帮助。

在您的循环中 $Product 不可访问尝试用 $query 替换:

$query->where('ProductSubCategory', '=', $Product Sub Category[$i]);