一切!我希望有人知道如何找到解决这个问题的方法。我加入了3个表,但是当我尝试通过join方法进行加入时,我无法获得相关的表格以及where语句根本不起作用。所以,我有一个方法
public static function get_by_abc($letter = null,
$object = false) {
$result = self::find()
->join('INNER JOIN', 'geo_place', 'geo_place.city_id = geo_city.id')
->join('INNER JOIN', 'bus_station', 'geo_place.place_id = bus_station.geo_place_id')
->join('INNER JOIN', 'bus_company', 'bus_station.company_id = bus_company.id')
//->innerJoinWith('companies')
->where(['bus_company.active' => 1])
->andWhere(['like', 'geo_city.name', $letter.'%', false]);
if(!$object) $result->asArray();
return $result->all(); //->createCommand()->rawSql
}
接下来,我试图通过yii2方法解决方案,但它也没有工作:(我看起来像
public function getCompanies() {
return $this->hasMany(BusCompany::className(), ['id' => 'company_id'])
->viaTable('bus_station', ['geo_place_id' => 'place_id'])
->viaTable('geo_place', ['city_id' => 'id']);
}
但在这种情况下,我加入了geo_place和bus_company,但没有加入bus_station。
所以表的结构如下所示:
答案 0 :(得分:0)
尝试像这样定义关系树:
public function getBusStation()
{
return $this->hasOne(BusStation::className(), [...]);
}
public function getBusCompanies()
{
return $this->hasMany(BusCompany::className(), ['id' => 'company_id'])->via('busStation'); // it will use your relation `getBusStation()` to join bus companies by this relation
}
易于维护和理解,希望它能帮到你。