我在这个话题中停留了一个小时,我没有看到任何我想念的东西。我正试图做一个懒惰的急切负荷:
$p = Project::all();
$p = $p->load('skills', 'user', 'comments', 'suggests');
var_dump($p->skills());
但是这会引发错误:
Call to undefined method Illuminate\Database\Eloquent\Collection::skills()
答案 0 :(得分:2)
不要将$ p-> load()分配给$ p。
$p = Project::all();
$p->load('skills', 'user', 'comments', 'suggests');
var_dump($p->skills());
答案 1 :(得分:0)
您在这里尝试load
关系而不是Model
,因为$p
包含Models
的集合,因此此代码无效
$p = Project::all();
$p = $p->load('skills', 'user', 'comments', 'suggests');
var_dump($p->skills()); <-- $p is a collection not a Model
您可以使用循环或使用集合中的索引来指定要加载关系的Model
,如:
$p = Project::all();
$p = $p->load('skills', 'user', 'comments', 'suggests');
// Get the first Model from collection and load it's first
// skill from collection of skills objects
dd($p->first()->skills()->first());
或使用索引指定集合中的项目,例如:
$skills = $p->get(2)->skills()->get(); // Get skills from second Project, 1st = 1
dd($skills->get(2)); // Get second skill item from collection of skills
您也可以运行循环
$p = Project::all();
foreach($p as $project) {
$skills = $project->skills()->get();
dd($skills->first());
dd($skills->get(2)) // 2nd item/skill, 1st = 1 (not 0)
// Or another loop
foreach($skills as $skill) {
// Use $skill->field_name
}
}