PHP: Laravel how to eager load find method

后端 未结 1 1792
灰色年华
灰色年华 2021-01-19 05:13

I have a model Users which has-many Pages, I want to eager load the method below so that it returns only a single user with all the pages eager loa

相关标签:
1条回答
  • 2021-01-19 05:54

    Drop the parenthesis.

    $user = User::find(1);
    $pages = $user->pages;
    foreach($pages as $page) {
        var_dump($page->name);
    }
    

    If you want to eager load it, then use the with method and pass the correct parameter, which would be the name of your relationship methods:

    $user = User::with('pages')->find(1);
    foreach($user->pages as $page) {
        var_dump($page->name);
    }
    
    0 讨论(0)
提交回复
热议问题