4

我有两张我想加入的桌子......即营地和城市。我已经为此用 PHP 编写了查询...但我想要 Yii2 格式的相同查询...请告诉我如何在 yii2 中编写此查询...??

这是我的查询:

SELECT DISTINCT camps.city_id, camps.state_id, cities.city_name 
    from camps 
    LEFT JOIN cities
    ON cities.state_id = camps.state_id
    WHERE camps.state_id = 5
    AND camps.status = '1'
    ORDER BY cities.city_name ASC
4

4 回答 4

4
use yii\db\Query;

$query  = new Query(); 
$query->select
                       (['camps.city_id AS City, camps.state_id AS State, cities.city_name AS Name'
                       ]) 
                      ->from('camps')
                      ->join('LEFT JOIN',' cities','cities.state_id = camps.state_id')
                      ->where('camps.state_id=:id',['id'=>5])
                      ->andWhere('camps.status=:no',['no'=>1]);


 $command   = $query->createCommand();
 $result    = $command->queryAll(); 
于 2015-06-24T07:28:03.980 回答
1

with 的等价物ActiveQuery可以是这样的:

Camp::find()
    ->select(['city_id', 'state_id', 'city_name'])
    ->distinct()
    ->joinWith('city')
    ->where([
        'state_id' => 5,
        'status' => 1,
    ])
    ->orderBy(['city_name' => SORT_ASC])
    ->all();

并添加与Camp模型的关系:

public function getCity()
{
    $this->hasOne(City::className(), ['state_id' => 'state_id']);
}

您可以在Active Record 部分找到文档:

于 2015-04-16T11:43:08.870 回答
0
$query = new Query();
    $query->select(['camps.city_id', 'camps.state_id',   'cities.city_name'])->
        from('cities')->
        innerJoin('camps','cities.state_id = camps.state_id')->
        where(['camps.state_id' => 5,'camps.status' => '1'])->all();
于 2015-05-14T15:28:04.740 回答
0

用这个,希望对你有帮助

$sql = " SELECT DISTINCT camps.city_id, camps.state_id, cities.city_name 
from camps 
LEFT JOIN cities
ON cities.state_id = camps.state_id
WHERE camps.state_id = 5
AND camps.status = '1'
ORDER BY cities.city_name ASC ";

$query = Yii::$app->db->createCommand($sql)->execute();
于 2015-05-18T05:18:51.723 回答