YII关联查询
2016-05-19 20:41
537 查看
以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次查询 */
相关文章推荐
- PHP $_SERVER参数详解
- ThinkPHP基础
- ContentProvider基础
- 为PHP7安装Windows Server 2012 R2过程记录
- 破解TP-Link路由-嗅探PPPoE拨号密码
- OSX给PHP添加pdo_mysql扩展
- PHP解决抢购、秒杀、抢楼、抽奖等阻塞式高并发库存防控超量的思路方法
- OSX为PHP添加mysql扩展
- phpexcel导出excel中文乱码问题解决
- OSX PHP添加gettext支持
- OSX PHP添加intl支持
- yii
- 解决OSX上面PHP curl SSLRead() error
- PHP函数用法
- 基于在生产环境中使用php性能测试工具xhprof的详解
- php aes 128 CBC加密、解密函数
- php函数
- VxWorks_使用ftp服务
- 2016/05/19 thinkphp 3.2.2 文件上传
- 基础总结篇之八:创建及调用自己的ContentProvider