Laravel Associated query articles and article authors

Source: Internet
Author: User
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

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.