【问题标题】:Store data into database using request json string in laravel在 laravel 中使用请求 json 字符串将数据存储到数据库中
【发布时间】:2021-02-28 02:17:27
【问题描述】:

我有一个表名 Student ( id , name , Division )。要将数据存储到此表中,我将 json 字符串作为请求发送到 laravel 中的 api。

请求的json字符串是,

{
"name":"abc",
"division":"a",
"city":"xyz"
}

控制器代码

 public function registerStudent(Request $request){

    $requestData = $request->json()->all(); 
    $studentModel = Student::create($requestData);

 }

学生模型

class Student extends Model
{
    protected $fillable = [
        'id', 'name','division'
    ];

   
}

当我执行此代码时,我收到以下错误,

Illuminate\Database\QueryException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'city' in 'field list' (SQL: insert into `Student`... 

现在我的问题是,我可以通过什么方式将数据从 json 请求存储到数据库中,并在 json 对象/数组中添加额外的键。

【问题讨论】:

  • 如果id 列设置为自动递增,则$fillable 数组中不需要它。

标签: json database laravel laravel-5


【解决方案1】:

您可以使用集合only 方法。

public function registerStudent(Request $request){

    $requestData = collect($request->json()->all())->only(['name', 'division']); 
    $studentModel = Student::create($requestData);

 }

【讨论】:

  • 你能用我的例子详细说明一下吗
  • 当然,您希望我具体说明什么?
  • 另外,您需要额外的数据吗?您是否只想存储idnamedivision
  • 是的,我需要来自用户的 api 中的额外数据,但请求中只使用名称、部门字段,其他进程将使用城市键。
  • 所以在调用Student::create 时不应存储city
猜你喜欢
  • 2018-09-21
  • 1970-01-01
  • 1970-01-01
  • 2021-06-10
  • 1970-01-01
  • 2017-02-12
  • 1970-01-01
  • 1970-01-01
  • 2012-02-17
相关资源
最近更新 更多