循环关系与急切加载

时间:2014-09-30 09:39:44

标签: php laravel laravel-4 eloquent

我有Category模型定义了关系:

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::with('entries')->find(8);

echo $category->name."<br />";
foreach ($category->entries as $e) {
    echo $e->domain."<br />";
}

我收到以下错误:

  

为foreach()提供的参数无效

如果我将代码更改为:

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

echo $category->name."<br />";
foreach ($category->entries() as $e) {
    echo $e->domain."<br />";
}

我没有得到任何错误,但是循环一次也没有执行。

如何在循环中显示数据以进行预先加载?在所有情况下,如果我在phpMyAdmin中手动运行查询,则运行几乎相同的数据库查询并且有数据。

1 个答案:

答案 0 :(得分:1)

您的模型必须发生碰撞,例如。使用

时调用的property / db字段/访问器
$category->entries;

因此它不会调用返回Collection的{​​{3}},可以在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)