Answer the question
In order to leave comments, you need to log in
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'
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');
}
$t = Tbl1::find()->byPk($id)->joinWith('tbl2')->one();
var_dump($t->tbl2);
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
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question