【问题标题】:Laravel - Undefined index in query builderLaravel - 查询构建器中的未定义索引
【发布时间】:2020-03-17 17:07:58
【问题描述】:

我有以下数组,我想将“main_id”键的所有值传递给 whereNotIn 条件:

array:7 [
  0 => array:1 [
    "main_id" => "KWS1354767"
  ]
  1 => array:1 [
    "main_id" => "KWS1348470"
  ]
  2 => array:1 [
    "main_id" => "KWS1300790"
  ]
  3 => array:1 [
    "main_id" => "KWS1267286"
  ]
  4 => array:1 [
    "main_id" => "KWS1260614"
  ]
  5 => array:1 [
    "main_id" => "KWS1259115"
  ]
  6 => array:1 [
    "main_id" => "KWS1145684"
  ]
]

我在控制器中的代码如下:

$search = $search->select("properties.prop_id as main_id")->get();
$searcharray = $search->toArray();
$prop_cnt = DB::table("offerdemandsmatchs")->whereNotIn('prop_id', $searcharray['main_id'])
            ->where('offerdemand_id', $o->id)
            ->get();

我得到的错误是:

ErrorException  : Undefined index: main_id

如果我手动传递数组,它可以工作:

$prop_cnt = DB::table("offerdemandsmatchs")->whereNotIn('prop_id', ['KWS1354767', 'KWS1348470', 'KWS1300790'])
           ->where('offerdemand_id', $o->id)
           ->get();

我无法从数组中获取值,如果我像在第一条语句中那样传递值,它会失败。 我如何手动传递数组值?我必须传递一个集合吗?

问候

【问题讨论】:

    标签: laravel laravel-5 eloquent


    【解决方案1】:

    使用 pluck 代替 select 然后转换成数组。

    Pluck 方法将为您创建一个数组。检查method pluck

    $prop_ids = $search->pluck('prop_id');
    //$prop_ids = ['KWS1354767','KWS1348470'..];
    $prop_cnt = DB::table("offerdemandsmatchs")->whereNotIn('prop_id', $prop_ids)
                ->where('offerdemand_id', $o->id)
                ->get();
    

    【讨论】:

    • 很高兴为您提供帮助:)
    【解决方案2】:

    它不起作用,因为您将错误的数组传递给语句。

    你必须做的是在搜索数组上使用array_column

    DB::table("offerdemandsmatchs")
        ->whereNotIn('prop_id', array_column($searcharray, 'main_id'))
        ->where('offerdemand_id', $o->id)
        ->get();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-10
      • 2018-08-02
      • 2012-08-24
      • 2015-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-07
      相关资源
      最近更新 更多