如何打印 id 特定数据?

我正在尝试打印与我的餐厅相关的菜肴。每道菜都分配了一个restaurant_id。


每个餐厅都分配了一个ID.


餐厅迁移


Schema::create('restaurants', function (Blueprint $table) {

        $table->bigIncrements('id');

        $table->string('name');

        $table->timestamps();

});

盘迁移


Schema::create('dishes', function (Blueprint $table) {

        $table->bigIncrements('id');

        $table->string('name');

        $table->float('price');

        $table->integer('restaurant_id');

        $table->string('image');

        $table->timestamps();

});

餐厅播种机


DB::table('restaurants')->insert([

        'name' => 'Bellos Pizzeria',

        'updated_at' => DB::raw('CURRENT_TIMESTAMP'),

    ]);


    DB::table('restaurants')->insert([

        'name' => 'McDonalds',

        'updated_at' => DB::raw('CURRENT_TIMESTAMP'),

    ]);


    DB::table('restaurants')->insert([

        'name' => 'Ericos',

        'updated_at' => DB::raw('CURRENT_TIMESTAMP'),

    ]);

播种机


    DB::table('dishes')->insert([

        'name' => 'Butter Chicken',

        'price' => '12',

        'restaurant_id' => 1,

        'image' => 'dishes_images/default.png',

        'updated_at' => DB::raw('CURRENT_TIMESTAMP'),

    ]);


    DB::table('dishes')->insert([

        'name' => 'Hamburger',

        'price' => '10',

        'restaurant_id' => 2,

        'image' => 'dishes_images/default.png',

        'updated_at' => DB::raw('CURRENT_TIMESTAMP'),

    ]);

个别餐厅视图上的 html


@section('content')

    <h1> {{$restaurant->name}} </h1>


    <a href="/assignment2/public/restaurant"> back </a>

@endsection  

我正在尝试打印与餐厅相关的菜肴。例如,id=1将在餐厅“Bellos Pizzeria”( ) 中列出的“Butter Chicken” ( id=1)。


慕森卡
浏览 131回答 2
2回答

慕容3067478

在Restaurant模型中编写关系代码。看到你上面的问题,我明白这种关系是一对多的关系。在这种情况下,请在餐厅模型中写下这个。餐厅.phppublic function dishes(){&nbsp; &nbsp; return $this->hasMany(Dish::class);&nbsp; &nbsp; //it define the relation type between Restaurant and Dish model}刀片文件<h1> {{$restaurant->name}} </h1><ul>&nbsp; &nbsp; @foreach($restaurant->dishes as $dish)&nbsp; &nbsp; &nbsp; &nbsp; <li>{{ $dish->name }}</li>&nbsp; &nbsp; @endforeach</ul>$restaurant->dishes将返回与餐厅相关的所有相关菜肴的数组/集合。用于@foreach显示所有菜肴。用户自己的Html,我用ul li的例子。

莫回无

您应该尝试使用 laravel 关系。喜欢创建Restaurants和Dishes建模。在您的餐厅模型中:class Restaurants extends Model{&nbsp; &nbsp; function dishes() {&nbsp; &nbsp; &nbsp; return $this->hasMany('App\Dishes');&nbsp; &nbsp; }}在您的菜肴模型中class Dishes extends Model{&nbsp; &nbsp; function restaurants() {&nbsp; &nbsp; &nbsp; return $this->hasMany('App\Restaurants');&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP