从两个不同的表中获取值,并将其放在Laravel的视图中 [英] Retrieve values from 2 different tables and put them in a view with Laravel

查看:108
本文介绍了从两个不同的表中获取值,并将其放在Laravel的视图中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个表格食物


  • Food_id(pk)

  • 食物名称

  • 描述

  • 图片

  • 价格

  • Food_id(pk)
  • Foodname
  • Description
  • Image
  • Price

其他表格是餐厅


  • Res_id (pk)

  • ResName

  • 位置

我将数据透视表 food_restaurant 设为:


  • id

  • Food_id fk)

  • Res_id(fk)

我想显示餐厅的位置以及食物在我的视图中的细节。因为我在模型 Food.php 中的功能作为

I want to show Location of Restaurant along with food details in my view.For that I make function in model Food.php as

public function restaurant()
{
    return $this->belongsToMany('App\Restaurant','food_restaurant','Food_id','Res_id');

}

其他型号 Restaurant.php 作为

public function food()
{
    return $this->belongsToMany('App\Food','food_restaurant','Res_id','Food_id');
}

我的控制器是:

class Detailscontroller extends Controller

      {
       public function index()

       {

       $Foods= Food::all();

       return view('welcome', compact('Foods'));

       }
      public function show($Food_id)

       {
   $food =Food::findOrFail($Food_id);

       return view('show', compact('food'));

       }

       }

路由是:

Route::get('/','DetailsController@index');

Route::get('/{Food_id}', 'DetailsController@show');

查看 welcome.blade.php 是:

@extends('layouts.app')

     @section('content')

     <div class="container">

      <div class="row">

       <div class="col-md-10 col-md-offset-1">

      @foreach($Foods as $Food)

    <p><img src="{{ asset('uploads/'.$Food->Image) }}" /><p>
     <Food>

     <h2>
      <a  href="/{{$Food->Food_id}}">{{$Food->FoodName}}
     <i class="fa fa-chevron-circle-right"></i></a
      </h2>
      </Food>

      @endforeach            

            </div>          
      </div>

        @endsection

And show.blade.php 是:

And show.blade.php is:

@extends('layouts.app')

@section('content')

<h1 align="center">{{$food -> FoodName}}</h1>

<p><img src="{{ asset('uploads/'.$food->Image) }}" /><p>

 <detail>
 <h3><p>FoodDescription:</h3><h4>{{$food->Description}}</h4></p>

 <h3><p>Price:</h3><h4>{{$food->Price}}</h4></p>

 @foreach ($food->restaurant as $restaurant) 

 <h3><p>Location:</h3><h4>{{$restaurant->Location}}</p></h4>

 @endforeach 

 @endsection

但是它不显示我的位置。我如何在我的show.blade.php视图中显示位置?我是新的laravel.Where是什么问题?

But it does not show Location to me.How can I show Location in my show.blade.php view?I am new to laravel.Where is the problem?

推荐答案

将食物数组返回到带有关联餐厅的视图。

return the food array to the view with associated restaurant.

public function show($Food_id)
{
   $food = Food::with('restaurant')->findOrFail($Food_id);
   return view('show', compact('food'));
}

这篇关于从两个不同的表中获取值,并将其放在Laravel的视图中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆