yii框架数据库关联查询操作示例(2)
控制器代码:
namespace app\controllers;
use yii\web\Controller;
use app\models\Order;
class CustomerController extends Controller{
//根据订单查询用户信息
public function actionIndex(){
$orders = Order::find()->where(['id'=>2])->one();
$customer = $orders->customer;
print_r($customer);
}
}
以上代码中的$orders->customer会记录缓存,如果要删除缓存,可以使用unset($orders->customer)。
关联查询的多次查询
$customers = Customer::find()->all();
foreach($customers as $customer){
$orders = $customer->orders;
}
这样如果有100条数据,就总共需要查询101次。
优化:
$customers = Customer::find()->with('orders')->all();
foreach($customers as $customer){
$orders = $customer->orders;
}
总共查询两次。
更多关于Yii相关内容感兴趣的读者可查看本站专题:《Yii框架入门及常用技巧总结》、《php优秀开发框架总结》、《smarty模板入门基础教程》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》
希望本文所述对大家基于Yii框架的PHP程序设计有所帮助。
