如何打印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"(id=1(上列出。

Restaurant模型中编写关系代码。看到你上面的问题,我明白这种关系是一对多的关系。在这种情况下,请在餐厅模型中写下此内容。

餐厅.php

public function dishes(){
return $this->hasMany(Dish::class);
//it define the relation type between Restaurant and Dish model
}

刀片文件

<h1> {{$restaurant->name}} </h1>
<ul>
@foreach($restaurant->dishes as $dish)
<li>{{ $dish->name }}</li>
@endforeach
</ul>

$restaurant->dishes将返回与餐厅关联的所有相关菜肴的数组/集合。使用@foreach显示所有菜肴。

使用你自己的Html,我以ulli为例。

你应该尝试使用拉拉维尔关系。喜欢

创建RestaurantsDishes模型。

在您的餐厅模型中:

class Restaurants extends Model
{
function dishes() {
return $this->hasMany('AppDishes');
}
}

在您的碟子模型中

class Dishes extends Model
{
function restaurants() {
return $this->hasMany('AppRestaurants');
}
}

最新更新