这篇文章给大家介绍怎么在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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。