繁体   English   中英

Laravel 4:模型关联(属于)

[英]Laravel 4 : model assocation (belongsTo)

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

根据动态属性 ,应该可以从-> food> category获得数据

  • 我遵循了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) } }

看来您的关系倒转了。 您正在通过food寻求food_category 所以, foodfood_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 {

}

尝试快速加载:

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

我认为要解决此问题,您有两种选择:

Fisrt:

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

然后执行更优雅的{{ $food->category->name }}

第二:只需添加“ id”

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM