Home > Backend Development > PHP Tutorial > Laravel associates query articles and article authors

Laravel associates query articles and article authors

PHP中文网
Release: 2023-03-01 06:12:02
Original
1631 people have browsed it

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

Reply content:

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


Short answer: You need to use Eager Loading

Long answer:


Query and traverse like the following, If 10 pieces of articledata are returned, a total of 11 SQLstatements will be executed. The first one is to query all 10 pieces of articledata at once. In addition, each traversal will execute once to obtain the corresponding authordata SQLquery (the reason is that Eloquentdefaults 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;
}
Copy after login

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;
}
Copy after login

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

Laravel related query problem

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template