OctoberCMS Rainlab.Builder- 与同一模型的 "hasOne" 关系错误

OctoberCMS Rainlab.Builder- Error on "hasOne" relation to same model

我正在开发用于管理动物的 October 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

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


代码

我实现了以下 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

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

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

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

mother_idfather_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。在您的情况下,您不必定义 keyotherKey,因为 otherKey 的默认值是 "id" 并且 otherKey 值是从关系名称创建的“_id”后缀。