Model->insert($data) 未将数据插入数据库

问题描述 投票:0回答:1

我正在使用 CodeIgniter v4.4.1。我正在尝试将客户插入到我的 MySQL 数据库中。我的 Customer 表目前只有两列(用于测试):

idcustomer
(主键,不为空,自动增量)和
name 
(varchar(45))。效果很好。

我的

Customer 
模型看起来像这样:

<?php namespace App\Models;

use CodeIgniter\Model;

class Customer extends Model
{
    protected $table = 'customers';
    protected $primaryKey = 'idcustomer';
    protected $returnType = 'array';
    protected $useTimestamps = false;
    protected $allowedFields = ['name'];
}

在我的控制器中,

<?php

namespace App\Controllers;

use App\Controllers\BaseController;
// use CodeIgniter\Controller;
use App\Models\Customer;

class CustomerController extends BaseController
{
//...
    public function store()
    {
        $customerData = $this->request->getPost();

        // return view('customer/test', $customerData);
        // I used this line above to test if I had any data in $customerData, and I was able to access the data from the post request there. So up to here, everything is working fine.

        $customer = model('Customer');
    
        $customer->save([
            'name' => $customerData['name'],
        ]);

        return redirect()->to('/customers');
    }
//...
}

当我提交表单时,post请求提交成功,我什至被重定向到

/customers
路线(如控制器的
store()
方法所示)。但是,当我检查我的数据库时,没有插入新客户.数据库保持与以前相同...我本来希望在客户表中创建新记录。

我删除了所有验证来测试,但它仍然不起作用。我在可写/日志中没有收到任何错误、异常或任何内容。

所以,我尝试在我的控制器中执行此操作:

public function store()
    {
        $customerData = $this->request->getPost();
        $customer = model('Customer');
    
        $customer->save([
            'idcustomer' => 22, // that is, an ID number that does not exist yet in my database (the highest existing ID is 5)
            'name' => $customerData['name'],
        ]);

        return redirect()->to('/customers');
    }

当我再次提交表单时,现在创建了一个新条目,但是,它是使用

idcustomer 
= 6 创建的。

现在,当我这样做时:

$customer->save([
            'idcustomer' => 3, // an existing ID
            'name' => $customerData['name'],
        ]);

然后,带有

idcustomer = 3
的条目将被修改(如预期)。

我也尝试过

$customer->insert(...)
,但也不起作用。

所以,底线,我的问题是,为什么当我不传入

idcustomer
时,新记录没有插入到数据库中?

php codeigniter orm codeigniter-4
1个回答
0
投票

尝试像这样改变它:

public function store()
{
    $customerData = $this->request->getPost();
    $customer = new Customer(); // Instantiate the Customer model

    $customer->insert([
        'name' => $customerData['name'],
    ]);

    return redirect()->to('/customers');
}

© www.soinside.com 2019 - 2024. All rights reserved.