关联合检查询调控器中就可以如此写

正文实例陈诉了YII框架关联合检查询操作。共享给我们供大家参谋,具体如下:

以customer order五个表为例

涉嫌查询调控器中

$customer = Customer::find()->where->one();$orders = $customer->hasmany('orders',['customer_id']=>'id')->asArray;$orders = $customer->hasmany,['customer_id']=>'id')->asArray;

customer模型中

public function getOrders(){ $orders = $this->hasmany('orders',['customer_id']=>'id')->asArray;}

关系查询调整器中就足以这样写

$customer = Customer::find()->where->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->one();$customer = $order->customer;

注意点

$customer = Customer::find()->where->one();unset;//清掉缓存$order = $customer->orders;

2.涉嫌查询的频仍询问

$customers = Customer::find;//select * from customerforeach($customers as $customer){$order = $customer->orders;//select * from order where customer_id = ...}

如上代码实行了101次sql查询,能够进行如下优化

$customers = Customer::find->all();//select * from customerforeach($customers as $customer){$order = $customer->orders();//select * from order where customer_id in }//变成了2次查询

更加多关于Yii相关内容感兴趣的读者可查阅本站专项论题:《Yii框架入门及常用本事总括》、《php卓绝开采框架总括》、《smarty模板入门功底教程》、《php面向对象程序设计入门教程》、《php字符串用法总括》、《php+mysql数据库操作入门教程》及《php何足为奇数据库操作技术汇总》

期望本文所述对大家基于Yii框架的PHP程序设计具有利于。

相关文章

发表评论

电子邮件地址不会被公开。 必填项已用*标注

*
*
Website