yii php 中的结 table

Junction table in yii php

我想创建一个联结 table tbl_guid_cost_centre 无需我手动将其保存到数据库即可得到处理。我尝试将此添加到我的关系中:

'costCentre' => [
            self::HAS_ONE,
            'CostCentre',
            'guid_to',
            'foreignKey' => 'guid',
            'tbl_guid_cost_centre(guid_to, cost_center_id)',
            "order" => "id desc"],

这样我在保存 costCentre 时,会在我的 tbl_guid_cost_centre 中为其创建一行。但是我收到错误:

Property "CHasOneRelation.0" is not defined.

有什么建议吗?

您对 HAS_ONE 关系的定义有误。关系配置数组的前三个元素应该是:关系类型、相关模型名称和外键定义。所有其他元素都应由与关系属性相关的键索引。 'tbl_guid_cost_centre(guid_to, cost_center_id)', 可能会产生这个错误,因为它没有键,所以它被当作 0 属性 的值。你没有分享任何细节,所以很难猜测你想要实现什么,但你应该从这样的事情开始:

'costCentre' => [
    self::HAS_ONE,
    'CostCentre',
    'guid_to',
    'order' => 'id desc',
],

并使用正确的键在数组末尾添加额外的设置。

您可以在文档中找到一些示例和解释:https://www.yiiframework.com/doc/guide/1.1/en/database.arr#declaring-relationship

您可以在您的关系中使用关键字 through 建立您的联结 table:

public function relations() {
        'guidCostCentre' => [
            self::HAS_ONE,
            'GuidCostCentre',
            ['guid_to' => 'guid']
        ],
        'costCentre' => [
            self::HAS_ONE,
            'CostCentre',
            'cost_centre_id',
            'through' => 'guidCostCentre'
        ]
    }