本文实例讲述了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次查询

更多关于yii相关内容感兴趣的读者可查看本站专题:《yii框架入门及常用技巧总结》、《php优秀开发框架总结》、《smarty模板入门基础教程》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》

希望本文所述对大家基于yii框架的php程序设计有所帮助。