2016-08-12 12 views
0

私はrecipTo Modelと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 
01を持っています

[{"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

を試してみてください。これが動作すれば私に教えてください。 – Shudmeyer

+0

それは働いた!ありがとうございました! – codi05ro

+0

聞いてもらえますが、これは1つのレコードでしか動作しません。あなたはカウンタを作成するか、@ linuxartisanが提供する答えを使用することができます – Shudmeyer

答えて

2

は、[0] $レシピに>食品を試してみてください。この

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

ありがとうございました!出来た! – codi05ro

関連する問題