0
votes

I'm trying to create a relation to a postgres array column in Yii2 and it's giving me an error (not surprisingly)

SQLSTATE[42883]: Undefined function: 7 ERROR: operator does not exist: integer[] = integer

Just setting the standard onCondition() doesn't seem to work.

Anyone have experience working with postgres array types and Yii2 relations? It would be nice if I could do something like this to override the default operator and on condition to support array column type.

/**
 * @return \yii\db\ActiveQuery
 */
public function getMyRelation()
{
    return $this->hasMany(ModelName::className(), ['@>', 'id', '{'.intval($this->rel_id).'}'])->alias('myRelation');
}
1

1 Answers

1
votes

You cannot create hasMany relation in this way - ActiveRecord does not support such syntax and you cannot use model attributes for defining relations, since this method may be executed before real model initialization (for example if you're building joins).

You may create getter which will use ActiveQuery to obtain related models - it will not be real relation and you will not be able to use it for eager loading or joins, but should work fine with lazy loading for single model:

public function getMyRelation() {
    $query = ModelName::find()
        ->andWhere(['@>', 'id', '{'. (int) $this->rel_id .'}'])
        ->alias('myRelation');
    $query->primaryModel = $this;
    $query->multiple = true;
    return $query;
}