Home > PHP Framework > YII > body text

How to use yii2 hasone

(*-*)浩
Release: 2019-11-07 09:57:56
Original
4007 people have browsed it

There are two types of associations between tables in Yii2, which are used to specify the association between two models.

How to use yii2 hasone

One-to-many: hasMany

One-to-one: hasOne (recommended learning: yii tutorial)

Return results: The return results of these two methods are yii\db\ActiveQuery objects

The first parameter: the class name of the associated model.

The second parameter: is an array, where the key is the attribute in the associated model and the value is the attribute in the current model.

Associated use

Now we get all the order information of a customer

$customer = Customer::findOne(1);  
$orders = $customer->orders; // 通过在Customer中定义的关联方法(getOrders())来获取这个客户的所有的订单。
Copy after login

The above two lines of code will generate the following sql statement

SELECT * FROM customer WHERE id=1;  
SELECT * FROM order WHERE customer_id=1;
Copy after login

Association result caching

If the customer's order changes, we call it again

$orders = $customer->orders;
Copy after login

When you get the order again, you will find that there is no change. The reason is that the database will only be queried when $customer->orders is executed for the first time, and the results will be cached, and sql will not be executed during subsequent queries.

So what if I want to execute sql again? You can execute

unset($customer->orders);  
$customer->orders;
Copy after login

and then you can fetch data from the database.

Code Description:

// 执行sql语句: SELECT * FROM customer WHERE id=1  
$customer = Customer::findOne(1);  
//执行sql:SELECT * FROM order WHERE customer_id=1  
$orders1 = $customer->orders;  
//这个不会执行sql,直接使用上面的缓存结果  
$orders2 = $customer->orders;
//如果中间的用户订单有变化,我们就不能从缓存中获取,要unset掉
unset($customer->orders);  
$orders2 = $customer->orders;
Copy after login

The above is the detailed content of How to use yii2 hasone. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template