Y
Y
Yuri2018-03-10 13:49:53
Yii
Yuri, 2018-03-10 13:49:53

How to connect two models by multiple fields in Yii2?

Greetings!
There are two tables that have type_id, min, max fields.
You need to link them like this:

SELECT * FROM `tbl1` LEFT JOIN `tbl2` ON (`tbl1`.`type_id` = `tbl2`.`type_id`) AND ((tbl2.min >= tbl1.min) AND (tbl2.max <= tbl1.max)) WHERE `tbl1`.`id`='1'

To do this, I wrote something like this:
public function getTbl2()
  {
    return $this->hasMany(Tbl2::class, ['type_id' => 'type_id'])
      ->andOnCondition(Tbl2::tableName() . '.min >= ' . self::tableName() . '.min')
      ->andOnCondition(Tbl2::tableName() . '.max <= ' . self::tableName() . '.max');
    }

When trying to display the value from tbl2 like this:
$t = Tbl1::find()->byPk($id)->joinWith('tbl2')->one();
var_dump($t->tbl2);

I am getting this error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'tbl1.min' in 'where clause'
The SQL being executed was: SELECT * FROM `tbl2` WHERE (`type_id`=1) AND ((tbl2.min>= tbl1.min) AND (tbl2.max <= tbl1.max))

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis, 2018-03-10
@Winter_Silence

return $this->hasMany(Tbl1::class, ['type_id' => 'type_id'])

looks suspicious maybe Tbl2::class
or so you are trying to jnoin yourself?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question