php - 我正在尝试将 restaurant_id 与菜肴联系起来
问题描述
我在两张桌子、餐厅和菜肴之间有一对多的关系。我无法将餐厅 ID 与菜肴相关联。我必须输入 user_id,但如果用户有不止一家餐厅,那么所有菜肴都会混合在一起。所以我应该用 restaurant_id 替换 user_id
菜控制器
class DishController extends Controller
{
public function index()
{
$dishes = Dish::all();
$restaurant = Restaurant::all();
$dishes = Dish::where('restaurant_id', Auth::id())->get();
return view('admin.dishes.index', compact('dishes', 'restaurant'));
}
public function create()
{
return view('admin.dishes.create');
}
public function store(Request $request, Restaurant $id)
{
$data = $request->all();
$data["restaurant_id"]= Auth::id();
/* $data['slug'] = Str::slug($data['name'], '-'); */
$new_dish = new Dish();
$new_dish->fill($data);
$new_dish->save();
return redirect()->route('admin.dishes.index', $new_dish);
}
public function show($id)
{
$dish = Dish::find($id);
if(!$dish){
abort(404);
}
return view('admin.dishes.show', compact('dish'));
}
public function edit($id)
{
$dish = Dish::find($id);
if (!$dish) {
abort(404);
}
return view('admin.dishes.edit', compact('dish'));
}
public function update(Request $request, Dish $dish)
{
$data = $request->all();
$dish->update($data);
return redirect()->route('admin.dishes.show',$dish);
}
public function destroy($id)
{
//
}
}
碟型
class Dish extends Model
{
protected $fillable = [
'name', 'ingredients', 'price', 'cover', 'visible','restaurant_id'
];
public function restaurant(){
return $this->belongsTo('App\Restaurant');
}
public function orders(){
return $this->belongsToMany('App\Order');
}
}
解决方案
您可以尝试在视图表单中向 restaurant_id 添加隐藏字段
<input type="hidden" name="restaurant_id" value={{ $restaurant->id }}>
然后,在您的商店方法中
$restaurant = Restaurant::find($request->restaurant_id);
$restaurant->dishes()->create( //Your Atribbutes here//);
推荐阅读
- performance - 负载测试中崩溃点和降级之间的区别
- c# - angular5/MVC 中的引导布局更改
- swift - “AVCapturePhotoOutput”类型的值没有成员“captureStillImageAsynchronously”
- java - Firestore:从firestore获取数据并从对象获取值并将其添加到listview
- git - 如何在 git 中修复“修改后的内容,未跟踪的内容”?
- aerospike - 如何从 Aerospike 恢复数据
- java - 我收到错误:选项 http://10.100.8.58:8080/user/view 401 () ,
- reactjs - 在 ReactJS 中将 HTML 文件转换为 PDF
- java - “adb shell date > date.txt”命令执行在 Mac 中使用 Process exec 不起作用
- ios - 如何快速隐藏嵌入在导航堆栈中的视图控制器中的选项卡栏?