CodeIgniter insert_batch: 字段 'exp_user' 没有默认值

CodeIgniter insert_batch: Field 'exp_user' doesn't have a default value

我正在尝试将一个数组作为一行插入到我的数据库中的 "expenses" table 中:

public function insert_expense($expenses){
    $this->db->insert_batch('expenses', $expenses); 
}

我不断收到此错误:

A Database Error Occurred
Error Number: 1364
Field 'exp_user' doesn't have a default value
INSERT INTO expenses () VALUES (), (), (), (), (), (), (), (), (), (), (), ()
Filename: models/Expenses_model.php
Line Number: 26

这是我的 table 的结构:

这是我要插入的示例:

array(12) {
    ["exp_user"] "1"
    ["exp_date"] "2016-10-18"
    ["exp_date_request"] "2016-10-18"
    ["exp_client"] "Potato"
    ["exp_provider"] "Miew"
    ["exp_amount"] "1"
    ["exp_currency"] "₪"
    ["exp_budget"] "budget2"
    ["exp_method"] "cc"
    ["exp_frequency"] "Monthly"
    ["exp_expenditure"] "asdasdas asdas dsa as"
    ["exp_charge_client"] NULL
}

如果变量 $expenses 是您示例中的数组:

$expenses = array(
    "exp_user" => "1",
    "exp_date" => "2016-10-18",
    "exp_date_request" => "2016-10-18",
    "exp_client" => "Potato",
    "exp_provider" => "Miew",
    "exp_amount" => "1",
    "exp_currency" => "₪",
    "exp_budget" => "budget2",
    "exp_method" => "cc",
    "exp_frequency" => "Monthly",
    "exp_expenditure" => "asdasdas asdas dsa as",
    "exp_charge_client" => NULL
);

您不能在 insert_batch 函数中使用它(因为 insert_batch 函数需要获取(数据的)数组数组作为第二个参数)。

基本上,insert_batch 函数使您能够插入多行(无需遍历 insert 函数)。您可以为此使用多维数组:

$expenses = array(
    array(
        "exp_user" => "1",
        "exp_date" => "2016-10-18",
        "exp_date_request" => "2016-10-18",
        "exp_client" => "Potato",
        "exp_provider" => "Miew",
        "exp_amount" => "1",
        "exp_currency" => "₪",
        "exp_budget" => "budget2",
        "exp_method" => "cc",
        "exp_frequency" => "Monthly",
        "exp_expenditure" => "asdasdas asdas dsa as",
        "exp_charge_client" => NULL
    ),
    array(
        "exp_user" => "1",
        "exp_date" => "2016-10-18",
        "exp_date_request" => "2016-10-18",
        "exp_client" => "Potato",
        "exp_provider" => "Miew",
        "exp_amount" => "1",
        "exp_currency" => "₪",
        "exp_budget" => "budget2",
        "exp_method" => "cc",
        "exp_frequency" => "Monthly",
        "exp_expenditure" => "asdasdas asdas dsa as",
        "exp_charge_client" => NULL
    ),
    array(
        "exp_user" => "1",
        "exp_date" => "2016-10-18",
        "exp_date_request" => "2016-10-18",
        "exp_client" => "Potato",
        "exp_provider" => "Miew",
        "exp_amount" => "1",
        "exp_currency" => "₪",
        "exp_budget" => "budget2",
        "exp_method" => "cc",
        "exp_frequency" => "Monthly",
        "exp_expenditure" => "asdasdas asdas dsa as",
        "exp_charge_client" => NULL
    )
);

现在可以使用 insert_batch

如果您只有 1 条记录要插入,您可以使用 insert 函数:

$this->db->insert('expenses', $expenses); 

或将调用更改为:

$this->db->insert_batch('expenses', array( $expenses ) );