0

I would like to create a junction table tbl_guid_cost_centre that gets taken care of without me manually saving it to the database. I tried adding this to my relations:

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

so that my when saving the costCentre, a row is created for it in my tbl_guid_cost_centre. However I'm getting the error:

Property "CHasOneRelation.0" is not defined.

Any suggestion?

Nicky Mirfallah
  • 1,004
  • 4
  • 16
  • 38

2 Answers2

2

You can have your junction table with the keyword through in your relations:

public function relations() {
        'guidCostCentre' => [
            self::HAS_ONE,
            'GuidCostCentre',
            ['guid_to' => 'guid']
        ],
        'costCentre' => [
            self::HAS_ONE,
            'CostCentre',
            'cost_centre_id',
            'through' => 'guidCostCentre'
        ]
    }
Nicky Mirfallah
  • 1,004
  • 4
  • 16
  • 38
0

You're defining HAS_ONE relation in a wrong way. The first three elements of relation configuration array should be: relation type, related model name and foreign keys definition. All further elements should be indexed by keys related to relation properties. 'tbl_guid_cost_centre(guid_to, cost_center_id)', probably generates this error, because it does not have a key, so it is treaded as a value for 0 property. You didn't share any details, so it is hard to guess what you want to achieve, but you should start from something like this:

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

And add additional settings at the end array with correct key.

Some examples and explanation you can find in the documentation: https://www.yiiframework.com/doc/guide/1.1/en/database.arr#declaring-relationship

rob006
  • 21,383
  • 5
  • 53
  • 74