PHP:Laravel如何急于加载查找方法 [英] PHP: Laravel how to eager load find method
本文介绍了PHP:Laravel如何急于加载查找方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个模型Users
,其中有很多Pages
,我想急于加载下面的方法,以便它仅返回一个渴望加载所有页面的用户,我该如何处理.
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 loaded, how do I go about it.
$user = User::find(1);
$pages = $user->pages();
foreach($pages as $page) {
var_dump($page->name);
}
我尝试但不起作用的内容,而是加载了所有内容:
What I tried but doesnt work, it loads everything instead:
$user = User::with('Pages')->get();
$pages = $user->pages();
推荐答案
删除括号.
$user = User::find(1);
$pages = $user->pages;
foreach($pages as $page) {
var_dump($page->name);
}
如果您希望加载它,请使用with
方法并传递正确的参数,该参数将是您的关系方法的名称:
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);
}
这篇关于PHP:Laravel如何急于加载查找方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文