postgresql - Eloquent 默认属性值 : $attributes or DB column default value?

标签 postgresql laravel eloquent doctrine

为 Eloquent 模型实现默认值的正确方法是什么?

我已经使用 Laravel 的迁移配置了我的数据库表。某些列指定了默认值。当将这些表与 Eloquent 模型结合使用时,根据所选的数据库驱动程序会发生不同的事情:

在 MySQL 中,当创建一个新模型并保存它时,会插入一个数据库行,该行具有未明确指定的每个属性的列默认值。 这就是我希望发生的事情。

然而,在 Postgres 和 SQLite 中,情况并非如此。抛出 PDOException:

[PDOException]
SQLSTATE[23502]: Not null violation: 7 ERROR: null value in column "some_column" violates not-null constraint
DETAIL: Failing row contains (1, 2, 3, 4, 5, 6, null, null, null, null, null, null, 7, 8, null, 9, null, null, 10, 11, 12, null).

我很清楚该列不可为空,并且不接受空值。但是我希望插入默认值而不是引发错误。

最佳答案

我建议您创建自己的直接扩展 Eloquent 的父模型,并让您的所有模型都扩展这个自定义父模型。

在自定义父级中,覆盖 performInsert() 方法以在插入之前删除 null 值。请务必从 Eloquent 源代码中复制整个方法,以免丢失过程中的任何重要步骤:

class MyModelParent extends Illuminate\Database\Eloquent\Model
{
    /**
     * Perform a model insert operation.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $query
     * @return bool
     */
    protected function performInsert(Builder $query)
    {
        if ($this->fireModelEvent('creating') === false) {
            return false;
        }

        ... // Be sure to copy all of it!

        // This is the change you'll make. Before, it was just:
        // $attributes = $this->attributes;
        $attributes = array_filter($this->attributes, function($val){
            return $val !== null;
        });

        ... // Be sure to copy all of it!

        return true;
    }
}

performUpdate() 应该可以很好地处理这个问题,因为它使用 getDirty() 来获取字段列表而不是直接访问属性。

当你这样做的时候,你应该考虑向 Laravel 提交一个补丁,这将使核心 Postgres 安全。

关于postgresql - Eloquent 默认属性值 : $attributes or DB column default value?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41450914/

相关文章:

php - Laravel - 排序的集合输出不是数组

php - 在 Laravel5 中使用 Eloquent 模型获取表值

sql - 将数组从 jsonb_array_elements_text() 转换为整数数组

ruby-on-rails - 如何在 Rails 3 和 postgres 中处理大整数

PostgreSQL/PGAdmin4 错误 : there is no unique constraint matching given keys for referenced table

php - 从组件/ Blade 中的 Controller 传递变量

ruby-on-rails - 如何在不加载所有记录的情况下从按特定属性排序的数据库中获取 "next"记录?

laravel - 如何监控 Laravel 队列是否正在运行?

javascript - Laravel 在加载时使用 javascript 获取 session

php - 内部消息系统 laravel 数据库设计