Query the article List at the same time to query the author of the article information, how to correlate the query, I wrote a 1-to-1 relationship in the model, in the view of the call, although feasible, but out of query statements a lot of query author's statements, how to query out
Reply content:
Query the article list at the same time to query the author of the article information, how to correlate the query, I wrote a 1-to-1 relationship in the model, in the view of the call, although feasible, but out of query statements a lot of query author's statements, how to query out
Short answer: You need to use eager Loading
Long answer:
such as the query and traversal, if the return of 10 article
data, there will be SQL
a total of 11 statements, the first one is a one-time query all 10 article
data, and each traversal will execute author
a query to obtain the corresponding data SQL
(because the Eloquent
default is Lazy Loading
, the query operation is only performed when the relational data is accessed).
$articles = App\article::all (); foreach ($articles as $article) { echo $article->author->name;}
If used Eager Loading
, the query is executed once, as in the bottom SQL
.
$articles = App\article::with (' author ')->get (), foreach ($articles as $article) { echo $article->author-> Name;}
Related articles:
About Laravel query problems with multiple conditions?
Laravel Associated queries get only part of the data for a management object
Laravel Associated Query problems