Search code examples
laraveleloquentwhere-in

Using whereIn with different column names (Eloquent)


I have an array $toolIds containing only tool_id I want to use for selection from the tools table but the column names do not match and therefore it fails. I read in another thread that it would work if the array for matching (toolsIds) would only contain one column but this is not the case. My (not working) code:

$tools = DB::table('tools')->select('id','title')
  ->whereIn('tool_id',$toolIds)
  ->get();

The JSON output for the two arrays is:

toolid: [{"tool_id":"1155"},{"tool_id":"1136"}]

tools: [{"id":"1155","title":"Shemar Zieme"},{"id":"1136","title":"Mr. Johnny Hagenes DDS"}]

Solution

  • In Laravel whereIn accepts only flat array without keys. See where clauses.

    You must pluck ids in $toolIds array as below: (with array_pluck)

    $toolIds = [
        ["tool_id"=>"1155"],
        ["tool_id"=>"1136"]
    ];
    
    $plucked_ids = array_pluck($toolIds, 'tool_id'); // $plucked_ids = ["1155", "1136"];
    
    $tools = DB::table('tools')->select('id','title')
      ->whereIn('id', $plucked_ids) // and we check tools.id column not tool_id.
      ->get();