首页 > 解决方案 > 我正在尝试将 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');
    }
}

在此处输入图像描述

标签: phpmysqllaravel

解决方案


您可以尝试在视图表单中向 restaurant_id 添加隐藏字段

<input type="hidden" name="restaurant_id" value={{ $restaurant->id }}>

然后,在您的商店方法中

$restaurant = Restaurant::find($request->restaurant_id);
$restaurant->dishes()->create( //Your Atribbutes here//);

推荐阅读