php SQLSTATE[23502]:非空冲突:7错误:列“project_id”中的null值违反了not-null约束

g9icjywg  于 2023-08-02  发布在  PHP
关注(0)|答案(1)|浏览(214)

我在php(Yii2框架)中有以下错误:
错误代码:

Integrity constraint violation – yii\db\IntegrityException
SQLSTATE[23502]: Not null violation: 7 ERROR: null value in column "project_id" violates not-null constraint
DETAIL: Failing row contains (853322, 395, 4, 2023, 5245.50, 1, null).
The SQL being executed was: INSERT INTO "db"."budget_report_by_project" ("month", "year", "category_id", "currency_id", "project_id", "value") VALUES (4, 2023, 395, 1, NULL, '5245.5') RETURNING "id"
Error Info: Array
(
    [0] => 23502
    [1] => 7
    [2] => ERROR:  null value in column "project_id" violates not-null constraint
DETAIL:  Failing row contains (853322, 395, 4, 2023, 5245.50, 1, null).
)

1. in /var/www/internal_system/vendor/yiisoft/yii2/db/Schema.php at line 676
2. in /var/www/internal_system/vendor/yiisoft/yii2/db/Command.php at line 1307– yii\db\Schema::convertException(PDOException, 'INSERT INTO "db"."budget_r...')
3. in /var/www/internal_system/vendor/yiisoft/yii2/db/Command.php at line 1168– yii\db\Command::internalExecute('INSERT INTO "db"."budget_r...')
4. in /var/www/internal_system/vendor/yiisoft/yii2/db/Command.php at line 424– yii\db\Command::queryInternal('fetch', null)
5. in /var/www/internal_system/vendor/yiisoft/yii2/db/pgsql/Schema.php at line 646– yii\db\Command::queryOne()
6. in /var/www/internal_system/vendor/yiisoft/yii2/db/ActiveRecord.php at line 604– yii\db\pgsql\Schema::insert('db.budget_report_by_projec...', ['month' => 4, 'year' => 2023, 'category_id' => 395, 'currency_id' => 1, ...])
7. in /var/www/internal_system/vendor/yiisoft/yii2/db/ActiveRecord.php at line 570– yii\db\ActiveRecord::insertInternal(null)
8. in /var/www/internal_system/vendor/yiisoft/yii2/db/BaseActiveRecord.php at line 676– yii\db\ActiveRecord::insert(true, null)
9. in /var/www/internal_system/models/BudgetReportProject.php at line 463– yii\db\BaseActiveRecord::save()
457458459460461462463464465466467468469

字符串
代码:

$budgetItem->category_id = $item['category_id'];
$budgetItem->currency_id = $item['currency_id'];
$budgetItem->project_id = $item['project_id'];
$budgetItem->value = $item['value'];
if (!is_null($budgetItem->project_id))
{
    if (!$budgetItem->save())
    {
        $result['error'] = $budgetItem->getErrorMessge();
        return $result;
    }
}
unset($budgetItem);


为了防止这种情况,我已经添加了以下行:

if (!is_null($budgetItem->project_id))


它应该检查ID project_id是否为NOT NULL并进行保存。但上面的代码(空检查比较)似乎不起作用。如果project_id为null,则应返回TRUE,因此将不会执行以下代码来保存项:

if (!$budgetItem->save())
{
        $result['error'] = $budgetItem->getErrorMessge();
        return $result;
}


它被 Package 到'if'块中,以在发生错误时返回错误消息。
我希望如果project_id值为NULL,我可以简单地忽略它并避免将其添加到数据库中。然而,在这种情况下,空值检查似乎对我不起作用。
我还尝试将project_id值与NULL和null进行比较,但没有成功。
你能给点建议吗?

vcirk6k6

vcirk6k61#

建议您使用模型的validation rules(例如,您的用例所需的规则)。读取模型大量分配和模型加载方法。
您可以使用模型的validate()或保存()方法检查输入。

相关问题