Laravel 只考虑请求中的必填列,忽略任何其他键值(如果存在)

Laravel consider only the required columns from the request and ignore any other key values if present

在 Laravel API 中,我将请求输入 json 与一些额外的 key:values 一起传递,这是我在 [的业务逻辑的其他部分中需要的=49=]函数。当我将Controller函数的形参Request $request的数组$request->all()传给Model函数,直接传给Eloquentcreate()函数时如下:

StatusModel::create($request);

我收到错误,

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'app' in 'field list' (SQL: update tbl_points set team_id = 4, tour_id = 10, match_id = 254, win = 0, loss = 1, tie = 1, n_r = 1, pt = 1, nrr = 1, app = 3 where (team_id = 4 and tour_id = 10 and match_id = 254)).

我想按原样传递输入请求数组,并希望 laravel 忽略数组中不存在于数据库中的列名称键。 EG:以下是我的输入 json,其中 "app":3 是 table.

中不存在的额外键值
{
"team_id": 4,
"tour_id": 10,
"match_id": 254,
"win": 0,
"loss": 1,
"tie": 1,
"n_r": 1,
"pt": 1,
"nrr": 1,
"app": 3
}

我的模型代码

<?php

namespace App\Models\BaseModels;
use Illuminate\Database\Eloquent\Model;

class TablePoints extends Model
{   
    protected $table = 'tbl_points';    
    protected $fillable = ['team_id','tour_id','match_id','win','loss','tie','n_r','pt','nrr'];    
    public $timestamps = false;
}

在 dd($request->all()) 上,我在输出中得到以下内容:

array:10 [
  "team_id" => 4
  "tour_id" => 10
  "match_id" => 254
  "win" => 0
  "loss" => 1
  "tie" => 1
  "n_r" => 1
  "pt" => 1
  "nrr" => 1
  "app" => 3
]

如何通过使代码忽略额外的键值对来避免出现此类错误。

注意:我不想创建一个新数组并从请求数组中复制所需键的值并使用它。还有其他解决办法吗?

您应该在您的模型中声明一个受保护的 fillable 字段,它将包含您要向其中插入数据的所有字段。

您可以阅读更多相关信息here

你应该使用 except 函数。试试这个:

StatusModel::create($request->except('app'));

这将 return 除 app 字段之外的所有字段。

您也可以将它与数组一起使用以忽略多个字段。例如:

$request->except(['field1', 'field2']);

如果您需要排除所有不相关的数据,您可以使用这样的代码破解:

在状态模型中:

public function getFillable()
{
    return $this->fillable;
}

然后在Controller中,使用only方法过滤request中的属性:

$statusModel = new StatusModel();
$fields = $request->only($statusModel->getFillable());
$statusModel->fill($fields);
$statusModel->save();