Example of YII Framework Association Query Operation

  • 2021-12-11 06:59:02
  • OfStack

This article illustrates the YII framework associated query operation. Share it for your reference, as follows:

Take two tables customer order as examples

In the associated query controller


$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();

In the customer model (optimized)


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

You can write this in the associated query controller


$customer = Customer::find()->where('name'=>'zhangsan')->one();
$orders = $customer->getOrders();

You can even write it like this


$orders = $customer->orders;

The __get () magic method effect of the class is triggered when an undefined class property is obtained. YII is automatically called getOrders() Method, and it will be added ->all() , so define getOrders() You can't take it with you when you are all()

Order model


public function getCustomer(){
    $this->hasOne(Customer::className,['id'=>'customer_id'])->asArray();
}

This is written in the associated query controller


$order = Order::find()->where("id"=>'1')->one();
$customer = $order->customer;

Attention points

1. The associated query is cached

So


$customer = Customer::find()->where('name'=>'zhangsan')->one();
unset($customer->orders);// Clear the cache 
$order = $customer->orders;

2. Multiple queries of associated queries


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

The above code executes 101 sql queries and can be optimized as follows


$customers = Customer::find()->with('orders')->all();//select * from customer
foreach($customers as $customer){
$order = $customer->orders();//select * from order where customer_id in (...)
}// Become 2 Secondary query 

More readers interested in Yii can check the topics of this site: "Introduction to Yii Framework and Summary of Common Skills", "Summary of Excellent Development Framework of php", "Basic Tutorial of Introduction to smarty Template", "Introduction to php Object-Oriented Programming", "Summary of Usage of php String (string)", "Introduction to php+mysql Database Operation" and "Summary of Common Database Operation Skills of php"

I hope this article is helpful to PHP programming based on Yii framework.


Related articles: