获取引用对象的数据

时间:2016-08-12 10:54:02

标签: php mysql laravel reference

我有食谱模型和FoodComponent模型属于食谱。

RecipeModel:

class Recipe extends Model
{
    protected $table = 'recipes';

    protected $fillable = [ 
        'details'
    ];

    public function foods(){
            return $this->hasMany('App\FoodComponent','id','food_id');
    }
}

FoodComponent模型:

class FoodComponent extends Model
{
    protected $table = 'food_components';

    protected $fillable = [ 'title',
        'menu_id',
        'image'
    ];

    public function recipes(){
        return $this->belongsTo('App\Recipe','id','food_id');
    }
}

RecipeController:

public function index()
    {  
        $recipes = Recipe::all();

        return view('recipes.index')->with('recipes',$recipes);
    }

在视图中我有

@foreach($recipes as $recipe)
       {{ $recipe->foods }}
 @endforeach

我得到这样的东西:

[{"id":1,"menu_id":1,"title":"Pollo Locco","image":"images\/uploads\/foodcomponents\/99254.jpg","created_at":"2016-08-12 10:01:38","updated_at":"2016-08-12 10:01:38"}]

但我只想要'标题'。

我尝试过$ recipe-> foods-> title。但是没有用。

你能告诉我如何才能显示标题吗?

谢谢!

1 个答案:

答案 0 :(得分:2)

试试这个

@foreach($recipes as $recipe)
  @foreach($recipe->foods as $food)
   {{ $food->title }}
  @endforeach
@endforeach