There are two types of associations between tables in Yii2, which are used to specify the association between two models.
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())来获取这个客户的所有的订单。
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;
Association result caching
If the customer's order changes, we call it again
$orders = $customer->orders;
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;
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;
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!