Php 带急加载的循环关系

Php 带急加载的循环关系,php,laravel,laravel-4,eloquent,Php,Laravel,Laravel 4,Eloquent,我有定义了关系的类别模型: public function entries() { return $this->belongsToMany('Entry','entries_categories'); } 当我使用: $category = Category::find(8); echo $category->name."<br />"; $entries = $category->entries()->get(); foreach ($ent

我有定义了关系的
类别
模型:

public function entries() {
    return $this->belongsToMany('Entry','entries_categories');
}
当我使用:

$category = Category::find(8);

echo $category->name."<br />";
$entries  = $category->entries()->get();

foreach ($entries as $e) {
    echo $e->domain."<br />";
}
$category=category::find(8);
echo$category->name.“
”; $entries=$category->entries()->get(); foreach($e){ echo$e->domain.“
”; }
它工作正常-显示它应该显示的内容

但当我尝试使用“快速加载”时:

$category = Category::with('entries')->find(8);

echo $category->name."<br />";
foreach ($category->entries as $e) {
    echo $e->domain."<br />";
}
$category=category::with('entries')->查找(8);
echo$category->name.“
”; foreach($category->entries as$e){ echo$e->domain.“
”; }
我得到以下错误:

为foreach()提供的参数无效

如果我将代码更改为:

$category = Category::with('entries')->find(8);

echo $category->name."<br />";
foreach ($category->entries() as $e) {
    echo $e->domain."<br />";
}
$category=category::with('entries')->查找(8);
echo$category->name.“
”; foreach($category->entries()作为$e){ echo$e->domain.“
”; }
我并没有得到任何错误,但循环甚至并没有执行一次


如何在循环中显示数据以便快速加载?在所有情况下,对数据库的查询几乎都是相同的,如果我在phpMyAdmin中手动运行查询,则会有数据。

您的模型中必须存在冲突,例如使用时调用的property/db field/accessor

$category->entries;
因此,它不会调用返回可在foreach循环中使用的
集合的函数

// this works, because it explicitly calls the relation
foreach ($category->entries()-get() as $e)

// this would work the same way if there wasn't name collision
// because under the hood it would call
// $category->entries()->getResults(), which does the same as get() on this relation
foreach ($category->entries as $e)

您在
项调用中必须有一些冲突。您不能循环通过
entries()
,因为它是一个关系对象。但是,使用
belongToMany
时,只要
$category->entries
实际上将关系作为动态属性调用,就可以在foreach循环中始终使用它。也就是说,检查有什么冲突(访问器?属性?)顺便说一句,如果您想在cli中使用雄辩的artisan tinker,最好使用
artisan tinker
,而不是在浏览器中调用它。@JarekTkaczyk您可以将其添加为答案,我接受。我在数据库中的表中有一个
entries
列来存储属于该类别(迄今为止从未使用过)的条目数,这就是它不起作用的原因