获取参考物体的数据
问题描述:
我有一个Recipe Model和FoodComponent Model属于To Recipe。获取参考物体的数据
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。但没有工作。
你能告诉我一个想法吗?我该如何显示标题?
谢谢!
答
试试这个
@foreach($recipes as $recipe)
@foreach($recipe->foods as $food)
{{ $food->title }}
@endforeach
@endforeach
+0
非常感谢!有效! – codi05ro
试试这个$配方相关>食品[0] - >标题。让我知道这个是否奏效。 – Shudmeyer
它的工作!谢谢! – codi05ro
很棒的听到,但这只会在一个单一的记录。您可以创建一个计数器或使用@linuxartisan提供的答案 – Shudmeyer