Laravel firstOrNew 按特定 table 列

Laravel firstOrNew by a specific table column

我有一组来自前端的对象。我只想创建一个新的记录,如果数据库中还没有出现,但只能通过 primaryKey ('The_ID').

当我使用 firstOrNew 时,它会创建重复条目。

型号:

 protected $primaryKey = 'The_ID'; // Fake name.

 public $incrementing = true;

 public $timestamps = false;

 protected $fillable = [
   // all fields except the $primaryKey
 ];

控制器:

 $array = $request->lists;

 foreach ($array as $list) {
   ( new Model )->firstOrNew([
     'sue' => 'young',
     'foo' => 'bar',

     'datetimeadded' => \Carbon::now() // previous dev used this name :(
   ])->save();
 }

我想要的是,如果 The_ID 在数据库中,请不要保存。 The_ID 出现在请求中,因此我可以在循环中使用 $list['The_ID'] 访问它。

如果已经回答,请关闭。谢谢。

firstOrNew 接受 2 个数组。 1 基本上是您的 where 子句,第二个是您要插入的内容。通过仅使用 1 个数组,您基本上在所有内容中都有一个 where 子句。将您的代码修改为:

foreach ($array as $list) {
   ( new Model )->firstOrNew(
   ['id' => $request->id],
   [
     'sue' => 'young',
     'foo' => 'bar',

     'datetimeadded' => \Carbon::now() // previous dev used this name :(
   ])->save();
 }

我使用的第一个数组基本上是这样的:

where('id' ,'=',$request->id);
  • id: 你table,
  • 的PK
  • $request->id : 前端匹配的元素id 你的PK。

您也可以使用 updateOrCreate 来更新现有记录的当前字段或创建新记录。