How to use thinkphp5 association preloading

Recently, it has been developed using TP. I am puzzled by the association preloading of ->with and ->withJoin. The current record is summarized as follows:

The pre-query loading function of associative query solves the problem of optimal selection between performance and query, and mainly solves the problem of N+1 queries. Here is an example. If you query 3 results, you will perform 4 queries.

If you use the association pre-query function, for a one-to-one association, there is only one query, and for a one-to-many association, it can be turned into two queries, which effectively improves performance.

It can also support nested preloading, for example:

Version V5.0.7 or higher supports the use of arrays to define nested pre-loading. For example, the following pre-loading will simultaneously obtain the Phone, Job and Img sub-association model data of the user's Profile association model:

If you want to specify an attribute query, you can use a closure query:

 

Starting from V5.0.4+ version, one-to-one association preloading supports two methods: JOIN mode (one query) and IN mode (two queries). If you want to use the IN method to associate preloading, add it in the association definition method

In some cases, it is necessary to decide whether to use associative eager loading based on the queried data. Of course, associative query itself can solve this problem, because associative query is lazy, but the reason for using eager loading is also obvious. The performance has Advantage.

Delayed preloading is only for queries of multiple data, because there is no difference between lazy preloading and associated lazy queries for single data queries, so there is no need to use delayed preloading.

If your dataset query returns a dataset object, you can use load to call the dataset object to implement delayed preloading:

If your data set query returns an array, the system provides a load_relation helper function to accomplish the same function.

The problem I encountered in the project was that the association in the model was defined:

     Use ->with pre-query, but there is a problem with the result set of the query. The print SQL statement found that it is the default INNER JOIN, and I should use LEFT JOIN. After summarizing, the fifth parameter in blongsto is the association method, changed to LEFT OK 

Guess you like

Origin blog.csdn.net/EasyTure/article/details/109333525