You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Laravel Eloquent firstOrCreate方法出现SQL列不存在错误

解决Eloquent firstOrCreate 触发 Column not found 错误的问题

问题场景

使用Laravel的firstOrCreate方法创建Order模型实例时,出现列不存在的SQL错误:

$date = date("Y-m-d H:i:s");
$order = 
Order::firstOrCreate([
   ['name' => 'John'],
   [
       'type' => 'foo',
       'start' => $date,
   ]
]);

返回错误信息:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'John' in 'where clause' (SQL: select * from `orders` where (`John` is null and `foo` = 2022-09-20 15:15:54) and `orders`.`deleted_at` is null limit 1)

能看到Eloquent把值John当成了列名,而非预期的键name,问题出在哪?

错误原因与修复方案

你搞错了firstOrCreate的参数结构:

  • 该方法第一个参数是关联数组形式的查询条件,用来查找是否存在匹配记录
  • 第二个可选参数是创建新记录时的额外字段数组(如果找不到匹配记录时才会用到)

你的代码把查询条件和填充字段拆成两个嵌套数组塞进了第一个参数里,导致Eloquent解析参数时逻辑混乱,误把['name' => 'John']这个数组当成了键值对的键,进而把John识别成了列名。

正确写法1:区分查询条件与创建字段

如果只需要按name查找,找不到时再填充type和start:

$date = date("Y-m-d H:i:s");
$order = Order::firstOrCreate(
    ['name' => 'John'], // 仅按name查找匹配记录
    [
        'type' => 'foo',
        'start' => $date,
    ] // 无匹配时创建新记录的额外字段
);

正确写法2:所有字段作为查询条件

如果需要同时匹配name、type、start三个字段,找不到再创建:

$date = date("Y-m-d H:i:s");
$order = Order::firstOrCreate([
    'name' => 'John',
    'type' => 'foo',
    'start' => $date,
]);

内容的提问来源于stack exchange,提问作者Pingo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 00:35:29