将 whereIn 与不同的列名一起使用 (Eloquent)

Using whereIn with different column names (Eloquent)

我有一个仅包含 tool_id 的数组 $toolIds 我想用于从 tools table 中进行选择,但列名不匹配,因此失败.我在另一个线程中读到,如果匹配 (toolsIds) 的数组只包含一列,它会起作用,但事实并非如此。我的(不工作)代码:

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

两个数组的JSON输出是:

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

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

您可以使用 whereJsonContains 查询 JSON 个数组

关注laraveldocumentation:,希望对您有所帮助

In Laravel whereIn 只接受没有键的平面数组。参见 where clauses

您必须在 $toolIds 数组中提取 ID,如下所示:(使用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();