您好,登錄后才能下訂單哦!
這篇文章給大家介紹怎么在YII框架中實現關聯查詢,內容非常詳細,感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。
關聯查詢控制器中
$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模型中(優化)
public function getOrders(){ $orders = $this->hasmany('orders',['customer_id']=>'id')->asArray()->all(); }
關聯查詢控制器中就可以這么寫
$customer = Customer::find()->where('name'=>'zhangsan')->one(); $orders = $customer->getOrders();
甚至可以這么寫
$orders = $customer->orders;
當獲取未定義的類屬性時會觸發類的__get()魔術方法效果 YII會自動調用 getOrders()
方法,而且會加上->all()
,所以定義getOrders()
時不能帶上all()
Order模型
public function getCustomer(){ $this->hasOne(Customer::className,['id'=>'customer_id'])->asArray(); }
關聯查詢控制器中這么寫
$order = Order::find()->where("id"=>'1')->one(); $customer = $order->customer;
注意點
1.關聯查詢會被緩存
所以
$customer = Customer::find()->where('name'=>'zhangsan')->one(); unset($customer->orders);//清掉緩存 $order = $customer->orders;
2.關聯查詢的多次查詢
$customers = Customer::find()->all();//select * from customer foreach($customers as $customer){ $order = $customer->orders;//select * from order where customer_id = ... }
以上代碼執行了101次sql查詢,可以進行如下優化
$customers = Customer::find()->with('orders')->all();//select * from customer foreach($customers as $customer){ $order = $customer->orders();//select * from order where customer_id in (...) }//變成了2次查詢
關于怎么在YII框架中實現關聯查詢就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。