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

Laravel associates query articles and article authors

PHP中文网
PHP中文网Original
2017-03-21 16:18:231613browse

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;
}

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

Laravel related query problem

Statement:
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
Previous article:Class not foundNext article:Class not found