[英]How to print id specific data?
我正在嘗試打印與我的餐廳相關的菜餚。 每道菜都分配有一個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
我正在嘗試打印與餐廳相關的菜餚。 例如,將在餐廳“Bellos Pizzeria”( id=1
)上列出的“Butter Chicken”( id=1
=1)。
您應該嘗試使用 laravel 關系。 喜歡
創建Restaurants
和Dishes
Model。
在您的餐廳 Model:
class Restaurants extends Model
{
function dishes() {
return $this->hasMany('App\Dishes');
}
}
在你的菜 Model
class Dishes extends Model
{
function restaurants() {
return $this->hasMany('App\Restaurants');
}
}
在Restaurant
model 中編寫關系代碼。 看到你上面的問題,我明白這種關系是一對多的關系。 在這種情況下,請在餐廳 model 中寫入。
餐廳.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
,我以ul
li
為例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.