YII框架关联查询操作示例
发布:smiling 来源: PHP粉丝网 添加日期:2021-11-20 19:59:01 浏览: 评论:0
这篇文章主要介绍了YII框架关联查询操作,结合实例形式分析了Yii框架关联查询的实现方法及相关操作注意事项,需要的朋友可以参考下。
本文实例讲述了YII框架关联查询操作,分享给大家供大家参考,具体如下:
以customer order两个表为例
关联查询控制器中
- $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次查询
Tags: YII关联查询
相关文章
- ·Yii框架关联查询with用法分析(2021-05-01)
- ·详解YII关联查询(2021-07-05)
推荐文章
热门文章
最新评论文章
- 写给考虑创业的年轻程序员(10)
- PHP新手上路(一)(7)
- 惹恼程序员的十件事(5)
- PHP邮件发送例子,已测试成功(5)
- 致初学者:PHP比ASP优秀的七个理由(4)
- PHP会被淘汰吗?(4)
- PHP新手上路(四)(4)
- 如何去学习PHP?(2)
- 简单入门级php分页代码(2)
- php中邮箱email 电话等格式的验证(2)