Laravel 4:模型关联(belongsTo)

时间:2014-05-08 06:59:37

标签: php laravel eloquent model-associations

我与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 {

}

尝试从食物模型中提取类别信息时:

控制器中的

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,数据应该来自 - &gt;食物&gt;类别

  • 我遵循了laravel的命名惯例。
  • 数据存在于数据库中

http://s4.postimg.org/eog8nuf7x/Screen_Shot_2014_05_08_at_19_58_17.png

使用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) } }

======= UPDADED

添加预先加载时:

$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) } }

3 个答案:

答案 0 :(得分:1)

好像你的关系倒了。您要food_categoryfood。因此,food有一个food_categoryfood_category属于food,如果这应该是hasOnehasMany我无法从您的示例

数据库

foods table
  id
  name

food_categories table
  id
  name
  food_id

models / Food.php

class Food extends Eloquent {
    public function food_category()
    {
        return $this->hasOne('FoodCategory');
    }
}

模型/ FoodCategory.php

class FoodCategory extends Eloquent {

}

答案 1 :(得分:0)

尝试急切加载:

$foods = Food::with('FoodCategory')->get();

答案 2 :(得分:-1)

我想解决这个问题,你有两个选择:

Fisrt:

public function category()
{
    return $this->belongsTo('FoodCategory');
}

然后做{{ $food->category->name }}哪个更优雅

第二:只需添加'id'

public function food_category()
{
    return $this->belongsTo('FoodCategory','food_category_id');
}