如果值为空,CI 将使用默认字段插入数据库

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

我正在尝试插入到我的数据库表中。

我从专栏中收到此错误:

Column 'allow_edit_time_due' cannot be null

但是,该列设置为默认值:“0”

如果 'allow_edit_time_due' 为空,我怎样才能插入到我的表中,以便该值是默认值?

查询:

$sql = "INSERT INTO `cal_tasks` (user_id, task, task_notes, task_type, allow_edit_time_due, task_time_due, user_created) VALUES (" . $this->db->escape($user_id) . ", " . $this->db->escape($data['task']) . ", " . @$this->db->escape($data['task_notes']) . ", " . @$this->db->escape($data['task_type']) . ", " . @$this->db->escape($data['allow_edit_time_due']) . ", " . $this->db->escape($data['task_time_due']) . ", " . @$this->db->escape($data['user_created']) . ")";
php codeigniter
2个回答
0
投票

正如您所发现的,将 NULL 值传递给 SQL 会尝试用 NULL 值填充列,这会导致错误。

无论如何,使用活动记录将有助于简化您的代码(如果愿意的话)解决这个问题。所有值也会自动转义。

这是一个例子:

$cal_task = array(
    'user_id' => $user_id,
    'task' => $data['task'],
    'task_notes' => $data['task_notes'],
    'task_type' => $data['task_type'],
    'task_time_due' => $data['task_time_due'],
    'user_created' => $data['user_created']
);

// optional, default if null
if (isset($data['allow_edit_time_due']))
{
    $cal_task['allow_edit_time_due'] = $data['allow_edit_time_due'];
}

$this->db->insert('cal_tasks', $cal_task);

0
投票

在我们的一个项目中,我们决定将相当大的 Firebird 数据库迁移到 Postgres(遇到了几条龙!)。 Firebird 允许自动生成的主键和具有默认值的列为空,但 PSQL 不允许。

我们有许多执行插入和更新查询的模型方法,这些方法接收填充的有效负载对象。我们需要一个批量解决方案来在执行查询之前清理有效负载。出于显而易见的原因,我们不想破解任何驱动程序或核心文件。

我们当前使用的解决方案是将查找数组设置为配置项。关联数组的关联数组具有保存表名称的第一级键,然后第二级键是不接受

NULL
并且具有
DEFAULT
GENERATED
值的列的名称。不使用第二级值,但为了向开发人员提供清晰的说明,我们声明了默认值。

我们的 MY_Model 方法/签名类似于:

unsetNonNullablesWithNull(
    string $tableName,
    string $columnName,
    object $payload
): object {
    // loop and conditionally unset
}

如果有效负载中的任何列包含 NULL 值并且在查找数组中找到,则在返回对象之前从对象中取消设置它们。 我们所有其他模型都是从该模型扩展而来的,因此可以访问。

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