【发布时间】:2014-05-08 06:59:36
【问题描述】:
我与 laravel 4 有一个非常简单的表关联:
foods table
id
name
food_category_id
food_categories table
id
name
这是我的两个模型:
//models/Food.php
class Food extends Eloquent {
public function food_category()
{
return $this->belongsTo('FoodCategory');
}
}
//models/FoodCategory.php
class FoodCategory extends Eloquent {
}
当尝试从 Food 模型中提取类别信息时:
在控制器中:
class FoodController extends \BaseController {
public function index()
{
$foods = Food::all();
return View::make('admin/food/index',compact('foods'));
}
}
在视图中:
@foreach($foods as $food)
<tr>
<td>{{ $food->id }} </td>
<td>{{ $food->name }}</td>
<td>{{ $food->description}}</td>
<td>{{ $food->price}}</td>
<td>{{ $food->food_category->name }}</td>
</tr>
@endforeach
我收到以下错误消息:
试图获取非对象的属性(查看: /Library/WebServer/Documents/xxx/test/app/views/admin/food/index.blade.php)
基于dynamic properties,数据应该来自->food>category
- 我遵循 laravel 的命名约定。
- 数据库中存在数据
使用 dd(DB::getQueryLog()) 进行调试:
array(2) { [0]=> array(3) { ["query"]=> string(44) "select * from `users` where `id` = ? limit 1" ["bindings"]=> array(1) { [0]=> int(6) } ["time"]=> float(0.79) } [1]=> array(3) { ["query"]=> string(21) "select * from `foods`" ["bindings"]=> array(0) { } ["time"]=> float(0.32) } }
======= 更新
添加急切加载时:
$foods = Food::with('food_category')->get();
我明白了:
array(3) { [0]=> array(3) { ["query"]=> string(44) "select * from `users` where `id` = ? limit 1" ["bindings"]=> array(1) { [0]=> int(6) } ["time"]=> float(0.52) } [1]=> array(3) { ["query"]=> string(21) "select * from `foods`" ["bindings"]=> array(0) { } ["time"]=> float(0.42) } [2]=> array(3) { ["query"]=> string(67) "select * from `food_categories` where `food_categories`.`id` in (?)" ["bindings"]=> array(1) { [0]=> string(1) "1" } ["time"]=> float(3.23) } }
【问题讨论】:
-
您是在视图中调用它吗?
-
是的,我对所有元素使用了一个 foreach 循环 @foreach($foods as $food) 并用 {{ $food->food_category->name }} 调用它
-
所以
$food就是Food::find(),对吧?你能发布给你错误的实际代码吗?如何在控制器中调用它以及如何/传递给视图的内容 -
我已经更新了我的问题。谢谢
-
你的关系没问题。您似乎没有与
FoodCategory中的一个或一些Food模型相关的FoodCategory。还可以像建议的那样使用急切加载来避免 N+1 问题,但这里不是这种情况。您可以通过在您调用类别名称的位置添加is_null($food->food_category)来检查
标签: php laravel eloquent model-associations