本文實(shí)例講述了YII框架關(guān)聯(lián)查詢操作。分享給大家供大家參考,具體如下:
以customer order兩個(gè)表為例
關(guān)聯(lián)查詢控制器中
$customer = Customer::find()->where('name'=>'zhangsan')->one();
$orders = $customer->hasmany('orders',['customer_id']=>'id')->asArray()->all();
$orders = $customer->hasmany(Order::className(),['customer_id']=>'id')->asArray()->all();
customer模型中(優(yōu)化)
public function getOrders(){
$orders = $this->hasmany('orders',['customer_id']=>'id')->asArray()->all();
}
關(guān)聯(lián)查詢控制器中就可以這么寫(xiě)
$customer = Customer::find()->where('name'=>'zhangsan')->one();
$orders = $customer->getOrders();
甚至可以這么寫(xiě)
$orders = $customer->orders;
當(dāng)獲取未定義的類屬性時(shí)會(huì)觸發(fā)類的__get()魔術(shù)方法效果 YII會(huì)自動(dòng)調(diào)用 getOrders()
方法,而且會(huì)加上->all()
,所以定義getOrders()
時(shí)不能帶上all()
Order模型
public function getCustomer(){
$this->hasOne(Customer::className,['id'=>'customer_id'])->asArray();
}
關(guān)聯(lián)查詢控制器中這么寫(xiě)
$order = Order::find()->where("id"=>'1')->one();
$customer = $order->customer;
注意點(diǎn)
1.關(guān)聯(lián)查詢會(huì)被緩存
所以
$customer = Customer::find()->where('name'=>'zhangsan')->one();
unset($customer->orders);//清掉緩存
$order = $customer->orders;
2.關(guān)聯(lián)查詢的多次查詢
$customers = Customer::find()->all();//select * from customer
foreach($customers as $customer){
$order = $customer->orders;//select * from order where customer_id = ...
}
以上代碼執(zhí)行了101次sql查詢,可以進(jìn)行如下優(yōu)化
$customers = Customer::find()->with('orders')->all();//select * from customer
foreach($customers as $customer){
$order = $customer->orders();//select * from order where customer_id in (...)
}//變成了2次查詢
更多關(guān)于Yii相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Yii框架入門及常用技巧總結(jié)》、《php優(yōu)秀開(kāi)發(fā)框架總結(jié)》、《smarty模板入門基礎(chǔ)教程》、《php面向?qū)ο蟪绦蛟O(shè)計(jì)入門教程》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫(kù)操作入門教程》及《php常見(jiàn)數(shù)據(jù)庫(kù)操作技巧匯總》
希望本文所述對(duì)大家基于Yii框架的PHP程序設(shè)計(jì)有所幫助。
您可能感興趣的文章:- Yii2增刪改查之查詢 where參數(shù)詳細(xì)介紹
- Yii多表聯(lián)合查詢操作詳解
- YII2數(shù)據(jù)庫(kù)查詢實(shí)踐
- yii數(shù)據(jù)庫(kù)的查詢方法
- Yii2中多表關(guān)聯(lián)查詢hasOne hasMany的方法
- 詳解YII關(guān)聯(lián)查詢
- Yii2.0表關(guān)聯(lián)查詢實(shí)例分析
- 詳解Yii2.0使用AR聯(lián)表查詢實(shí)例
- Yii框架連表查詢操作示例
- Yii框架數(shù)據(jù)庫(kù)查詢、增加、刪除操作示例
- Yii框架where查詢用法實(shí)例分析