works:programmer:php:yii2-for-dummies

Yii2 для чайников

FIXME Ещё в разработке

SQL

Запрос SELECT

# Получить SQL код
# SELECT * FROM `table1` `t1` LEFT JOIN `table2` `t2` ON t2.t1id = t1.id
# LEFT JOIN `table3` `t3` ON t3.id = t2.table3_id WHERE (`t1`.`id`=:qp0) AND (t3.name="raw")
$sql = (new \yii\db\Query)
    -> select('*')
    -> from('table1 t1')
    -> leftJoin('table2 t2', 't2.t1id = t1.id')
    -> leftJoin('table3 t3', 't3.id = t2.table3_id')
    -> where(['t1.id' => 80])
    -> andWhere('t3.name="raw"')
    -> createCommand()->getSql();
 
# Примеры where
    -> andWhere('>=', 'sc.date_from', $date_from]) #   x >= $date_from
    -> andWhere('<=', 'sc.date_from', $date_to]) # y <= $date_to
    -> andWhere('!=', 'sc.active', 0 ])  # z != 0
    -> andWhere(['id' => [1, 2, 3]]) # where id in (1, 2, 3)
    -> andWhere(['not in', 'nid', [1, 2, 3]]); # where nid not in (1, 2, 3)

 
# Строк получено цифрой
$count = (new \yii\db\Query)->from('table1')->count();
 
# Всё массивом
$array = (new \yii\db\Query)->from('table1')->all();
 
# Одно значение в 1м поле 1й строки
$passwd = (new \yii\db\Query)->select('passwd')->from('table')->where(['id'=>5])->scalar()
 
# Массив из 1й колонки
$arr = (new Yii\db\Query)->from('private')->groupBy('user_id')->orderBy('user_id')->select('user_id u')->column();

Запрос INSERT

# Примеры insert
# Вставить 1 строчку
$success = \Yii::$app->db->createCommand()
                        ->insert('phonebook', ['name' => 'Test', 'phone' => '+371 27777776' ])
                        ->execute();
# Вставить много
$success = \Yii::$app->db->createCommand()
                        ->batchInsert('phonebook', ['name', 'phone'], [
                            ['Test1', '+371 27777777'],
                            ['Test2', '+371 27777778']
                        ])->execute();
works/programmer/php/yii2-for-dummies.txt · Last modified: 2018/12/15 17:18 (external edit)