0

我正在开发一个用于管理动物的十月 CMS 插件(使用 rainlab.builder)。动物有几个领域和关系。每只动物都有父亲和母亲。但是当我试图保护我的动物时,会出现以下错误:

事件簿:

PDOException: SQLSTATE[23000]: Integrity constraint violation: 1048
Column 'id' cannot be null in dir/website/vendor/laravel/framework/src/
Illuminate/Database/Connection.php:413

插件动物形态:

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'id'
cannot be null (SQL: update `prefix_animals_animal` set `id` =  where
`prefix_animals_animal`.`id` = 1 and `prefix_animals_animal`.`id` is 
not null)" on line 666 of dir/website/vendor/laravel/framework/
src/Illuminate/Database/Connection.php

该错误仅在我使用关系(孩子 -> 父亲,孩子 -> 母亲)时出现。


代码

我已经实现了以下与我的动物模型的 hasOne 关系:

/* Relation */

public $hasOne = [
    'father' => [
        'Namespace\Animals\Models\Animal',
        'key' => 'id',
        'otherKey' => 'id'
    ],
    'mother' => [
        'Namespace\Animals\Models\Animal',
        'key' => 'id',
        'otherKey' => 'id'
    ]
];

这是我来自field.yaml的字段:

father:
    label: Father
    oc.commentPosition: ''
    nameFrom: name
    descriptionFrom: description
    emptyOption: 'No father'
    span: left
    type: relation
mother:
    label: Mother
    span: right
    oc.commentPosition: ''
    nameFrom: name
    descriptionFrom: description
    emptyOption: 'No mother'
    type: relation

如果有人对这种关系有解决方案,我会很高兴。干杯!

4

1 回答 1

2

不要id用作关系的主键,因为这不是好的做法。

实际上,这也会产生您所看到的问题。目前,您的模型正在使用id主 ID、母亲 ID 和父亲 ID。你不能那样做。

mother_id将和添加father_id到 Animal 模型并将关系定义更改为:

public $hasOne = [
    'father' => [
        'Namespace\Animals\Models\Animal',
        'key' => 'father_id',
        'otherKey' => 'id'
    ],
    'mother' => [
        'Namespace\Animals\Models\Animal',
        'key' => 'mother_id',
        'otherKey' => 'id'
    ]
];

PS。在您的情况下,您不必定义默认值为“id”,并且该key值是从带有“_id”后缀的关系名称创建的。otherKeyotherKeyotherKey

于 2017-07-31T05:15:05.377 回答