【问题标题】:Enabling null on many FKs to same associated table在许多 FK 上为同一个关联表启用 null
【发布时间】:2022-08-19 02:45:13
【问题描述】:

我有多个字段设置为同一张表的 FK。 FK 也可以为 NULL。

我不断收到此错误:

ExistsIn rule for \'late_agreement_exception_outcome_recommendation_id\' is invalid. \'ExceptionOutcomes\' is not associated with \'App\\Model\\Table\\ExceptionsTable\'.

数据库结构:

exceptions
id,
request_id,
late_agreement_exception_outcome_recommendation_id (FK, exception_outcomes->id)
late_agreement_exception_outcome_id (FK, exception_outcomes->id),
...

exception_outcomes
id,
name
...

列定义(即late_agreement_exception_outcome_recommendation_id):

列关系(即late_agreement_exception_outcome_recommendation_id):

异常表:

FK 设置到 ExceptionOutcomes

$this->belongsTo(\'LateAgreementExceptionOutcomeRecommendations\', [
    \'class\' => \'ExceptionOutcomes\',
    \'foreignKey\' => \'late_agreement_exception_outcome_recommendation_id\',
    \'joinType\' => \'INNER\',
]);

编辑的规则试图为字段值启用空值输入:

$rules->add(
    function ($entity, $options) {
        $rule = new ExistsIn(\'late_agreement_exception_outcome_recommendation_id\', \'ExceptionOutcomes\');
        return $entity->late_agreement_exception_outcome_recommendation_id === NULL || $rule($entity, $options);
    },
    [\'errorField\' => \'late_agreement_exception_outcome_recommendation_id\']
);

更新#1

我像这样更改了关联名称:

$rules->add(
        function ($entity, $options) {
            $rule = new ExistsIn(\'late_agreement_exception_outcome_recommendation_id\', \'LateAgreementExceptionOutcomeRecommendations\');
            return $entity->late_agreement_exception_outcome_recommendation_id === NULL || $rule($entity, $options);
        },
        [\'errorField\' => \'late_agreement_exception_outcome_recommendation_id\']
    );

并简单地保存数据得到以下问题:

SQLSTATE[42S02]: Base table or view not found: 1146 Table \'sdi_ips2.late_agreement_exception_outcome_recommendations\' doesn\'t exist

以前,我可以在提供值时保存该列。但是,尝试恢复为 NULL 会导致问题。

更新#2

try
{
    $this->Requests->save($request);
}
catch(Cake\\Database\\Exception\\DatabaseException $e)
{
    debug(\"here!\");
    exit;
}

更新#3

这是我在 SQL 日志中看到的内容:

Generated Models
The following Table objects used Cake\\ORM\\Table instead of a concrete class:

LateAgreementExceptionOutcomeRecommendations
  • 你的关联名为LateAgreementExceptionOutcomeRecommendations,而不是ExceptionOutcomes,后者只是目标表的类名。
  • @ndm 请参阅更新 1。我根据您的建议对其进行了更改,但现在在提供值时无法保存。
  • 首先检查触发此错误的 SQL 查询到底是什么样的。
  • ps,您需要一个前导反斜杠来定义异常类的完全限定路径,否则它是相对于当前命名空间的,它不会捕获任何东西。
  • 啊,对了,协会班级的选项是className,不是class

标签: php cakephp cakephp-4.x


【解决方案1】:

解决方案:

注意belongsTo 中的className 属性。

$this->belongsTo('LateAgreementExceptionOutcomeRecommendations', [
    'className' => 'ExceptionOutcomes',
    'foreignKey' => 'late_agreement_exception_outcome_recommendation_id',
    'joinType' => 'INNER',
]);

【讨论】:

    猜你喜欢
    • 2011-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-30
    相关资源
    最近更新 更多