常用方法:
TableClass::find() ->返回yii\db\ActiveQuery Object
->select(string|array) ->要查詢的字段,如['id','name','age']
->where($condition(array|string), $params = []) ->查詢條件
->asArray() ->返回數組
->groupBy(string|array) ->分組eg:"id, name" 或 ["id, name")]
->distinct( true) ->是否去重
->limit(int) ->限制返回結果條數 eg:limit(3) 結果:limit 3
->offset(int) ->跳過 x 條數據 eg:->offset(3) 結果:offset 3
->orderBy(string|array) ->排序規則eg:id ASC, name DESC
或 ['id' => SORT_ASC, 'name' => SORT_DESC]
->scalar() ->查詢一個字段值,返回string
->one() ->查詢一條,返回array
->all() ->查詢所有,返回array
->count() ->查詢結果的條數,返回string|null|false|0
->sum(string); ->求和,eg:->sum("(local_num+taobao_num)");
1.查詢單條數據,返回類實例
:
ProductMovie::findOne(['id'=>'10']); //返回ProductMovie Object
ProductMovie::findOne(10); //默認where條件是 主鍵=>10
同
ProductMovie::find()->where(['id'=>'10'])->one(); //返回ProductMovie Object
2.查詢數據,返回數組
:
//asArray是yii\db\ActiveQueryTrait中的方法
//需要在DicineProductRecord 中 use yii\db\ActiveQueryTrait
Product::find()->where(['id'=>'1'])->asArray()->one(); //返回一維數組,單條數據
Product::find()->where(['id'=>'1'])->asArray()->all(); //返回二維數組,多條數據
3.查詢單個字段值
$res = DicineProductRecord::find()->select(['name'])->where(['id'=>8])->scalar();
$res返回值:string 蛋糕99
4.sql練習:
//use yii\db\ActiveQueryTrait
$query = Product::find();
$res = $query->where
([
'OR',
['AND','is_valid =1','id<3'],
['AND','is_deleted =0','name="蛋糕99"'],
['between','id',9,11],
])
->andFilterWhere([ 'like', 'product_name', $nameVal, false, ]) // andFilterWhere(array) 如果你不確定$nameVal是否有值,可以這樣寫,如果$nameVal 沒值,函數不會將字段product_name查詢條件添加到sql語句的where條件中,這在篩選查詢時非常有用
->asArray()
->select(['name'])
->limit(10)
->offset(1)
->orderBy('id DESC')
->distinct()
->all();
echo $query->createCommand()->getRawSql(); //打印sql語句
生成的sql:
SELECT DISTINCT `name` FROM `db_product` WHERE ((is_valid =1) AND (id<3)) OR ((is_deleted =0) AND (name="蛋糕99")) OR (`id` BETWEEN 9 AND 11) ORDER BY `id` DESC LIMIT 10 OFFSET 1
按固定順序排序
$query = Product::find();
$res =$query->where(
['id'=>[8,4,5,1,7]
])->asArray()
->orderBy(new Expression("FIELD(id,8,4,5,1,7)")) //按照id 8,4,5,1,7排序,field(str,str1,str2,str3)是mysql自定義的函數,SELECT FIELD("c", "a", "b", "c", "d", "e"); 返回字符串 c 在列表值中的位置->3
->select(['id','name'])
->limit(10)
->all();
//type=3的排在最前邊,type=1的排在第二,同時按id倒序
->orderBy(new Expression("case when type=3 then 1 when type=1 then 2 else 3 end,id desc"))
以下我們介紹where()方法當中,條件的拼裝方式。
#某個值爲null,會用IS NULL來生成語句:
['type' => 1, 'status' => 2] // 生成:(type = 1) AND (status = 2)
['id' => [1, 2, 3], 'status' => 2] // 生成:(id IN (1, 2, 3)) AND (status = 2)
['status' => null] // 生成:status IS NULL
['NOT', ['type' => null]] // 生成:type IS NOT NULL
#對比
['>', 'id', 1] // 生成:id > 1
['<', 'id', 100] // 生成:id < 100
['=', 'id', 10] // 生成:id = 10
['>=', 'id', 1] // 生成:id >= 1
['<=', 'id', 100] // 生成:id <= 100
['!=', 'id', 10] // 生成:id != 10
['and', 'id' => 1, 'id' => 2] // 生成:id=1 AND id=2
['and', 'id=1', 'id=2'] // 生成:id=1 AND id=2
['and', 'type=1', ['or', 'id=1', 'id=2']] // 生成:type=1 AND (id=1 OR id=2)
['or', ['type' => [7, 8, 9]], ['id' => [1, 2, 3]]] // 生成:(type IN (7, 8, 9) OR (id IN (1, 2, 3)))
['not', ['attribute' => null]] // 生成:NOT (attribute IS NULL)
['between', 'id', 1, 10] // 生成:id BETWEEN 1 AND 10
['not between', 'id', 1, 10] // 生成:id NOT BETWEEN 1 AND 10
['in', 'id', [1, 2, 3]] // 生成:id IN (1, 2, 3)
['id' => [4, 8, 15]] // 生成:id IN (4, 8, 15)
['not in', 'id', [1, 2, 3]] // 生成:id NOT IN (1, 2, 3)
['in', ['id', 'name'], [['id' => 1, 'name' => 'foo'], ['id' => 2, 'name' => 'bar']]] // 生成:(`id`, `name`) IN ((1, 'foo'), (2, 'bar'))
#用子查詢作爲IN條件的值,如下:
['in', 'user_id', (new Query())->select('id')->from('users')->where(['active' => 1])]
['like', 'name', 'tester'] // 生成:name LIKE '%tester%'
['like', 'name', ['test', 'sample']] // 生成:name LIKE '%test%' AND name LIKE '%sample%'
['like', 'name', '%tester', false] // 生成:name LIKE '%tester',false表示自定義like條件,加上false後,程序不會在數組的第三個參數tester兩側增加'%'
// 這是自定義查詢方式,要傳入值爲false的運算數3,並且自行添加%
['or like', 'name', ['test', 'sample']] // 生成:name LIKE '%test%' OR name LIKE '%sample%'
['not like', 'name', 'tester'] // 生成:name NOT LIKE '%tester%'
['or not like', 'name', ['test', 'sample']] // 生成:name NOT LIKE '%test%' OR name NOT LIKE '%sample%'
['exists', (new Query())->select('id')->from('users')->where(['active' => 1])] // 生成:EXISTS (SELECT "id" FROM "users" WHERE "active"=1)
5.插入數據:
插入多條數據:
\Yii::$app->db->createCommand()->batchInsert(Product::tableName(), ['name', 'age'], [
['Tom', 30],
['Jane', 20],
['Linda', 25],
])->execute();
插入一條:
$product = new Product();
$product->setAttributes($common);
$product->save();
6.更新數據表:
1.更新數值:在原來基礎上增加+或減少-
ActiveRecord::updateAllCounters($counters, $condition = '', $params = []);
//updateAllCounters更新符合 $condition條件的所有數據
$res =Product::updateAllCounters(['sale_num' => -3],['>','id' , 743]);
//updateCounters只更新一條
$res =Product::findOne(['id' => 747])->updateCounters(['sale_num' => -3]);
或
$res = Product::find()->where(['id' => '747'])->one()->updateCounters(['sale_num' => -3]);
2.更新其他:
第一種:
$model = Product::findOne(['id' => 8]);
$model->setAttributes(['name' => '蛋糕']);
$res = $model->save();
第二種:function updateAll($attributes, $condition = '', $params = []){...}
ProductRecord::updateAll(
['name'=>'花雕1'],
['<','id','3']
);
7.刪除數據:
//物理刪除
Product::findOne(['id' => 8])->delete();
8.with關聯查詢:
在數據表類ProductClass中設置好關聯關係,比如關聯關係爲category
在ProductClass中定義方法getCategory()方法
eg:
public function getCategory()
{
return $this->hasOne(ProductCategory::class, [
'id' => 'category_id',
])->select(['id','name']);
}
查詢:
$condition = 0;
$query = Product::find();
$res = $query
->select('category_id')
->where(['<','id','6' ])
->with([
'category' => function ($query) use($condition) {
$query->where(['=','is_deleted',$condition]);
}
]) //關聯表設置條件is_deleted = 0
->asArray()
->all();
或 ->with( 'category' )->with('supply') //關聯表不設置查詢條件,需定義getSupply方法
或 ->with([
'category' => function ($query) {
$query->where(['=','is_deleted',0]);
}
])
返回結果:
Array(
[0] => Array
(
[category_id] => 1
[category] =>
)
[1] => Array
(
[category_id] => 4
[category] => Array
(
[id] => 4
[name] => 食品
)
)
)