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次查询

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

以上就是YII框架关联查询操作示例。长夜相识曾相伴,月华如水,繁花褪尽相思浅。孤守寒榻难入眠,愁心漫溢,只道故人心已变。晚安!更多关于YII框架关联查询操作示例请关注haodaima.com其它相关文章!

您可能有感兴趣的文章
Yii实现微信公众号场景二维码的方法实例

Yii使用DbTarget实现日志功能的示例代码

Yii使用EasyWechat实现小程序获取用户的openID的方法

Yii Framework框架开发微信公众平台示例

Yii 实现数据加密和解密的示例代码