Home >Backend Development >PHP Tutorial >Laravel associates query articles and article authors
Query the article list and query the author information of the article. How to associate the query? I wrote a 1-to-1 relationship in the model and called it in the view. Although it is feasible, the query statement contains many statements for querying the author. How? Query it out in one go
Query the article list and query the author information of the article. How to correlate the query? I wrote a 1-to-1 relationship in the model and called it in the view. Although it is feasible, But there are many query statements for querying the author. How can I query them all at once
Query and traverse like the following, If 10 pieces of article
data are returned, a total of 11 SQL
statements will be executed. The first one is to query all 10 pieces of article
data at once. In addition, each traversal will execute once to obtain the corresponding author
data SQL
query (the reason is that Eloquent
defaults to Lazy Loading
, and query operations are only performed when accessing relational data).
$articles = App\Article::all(); foreach ($articles as $article) { echo $article->author->name; }
If you use Eager Loading
, like below, the SQL
query will be executed once.
$articles = App\Article::with('author')->get(); foreach ($articles as $article) { echo $article->author->name; }
Related articles:
About the related query problem of multiple conditions in Laravel?
Laravel related query only obtains part of the data of the managed object