Создать регистр в двух разных таблицах в laravel - PullRequest
0 голосов
/ 21 мая 2019

Моя система создает блюдо с едой и сохраняет его в базе данных. Я хочу, чтобы к этому только что созданному блюду добавили один или несколько ингредиентов, выбранных с помощью флажка списка, уже сделанного динамическим.это будет видеть вид

, как вы можете видеть, я выбрал пиццу в качестве ранее созданного блюда.теперь мне нужно только добавить ингредиенты с их соответствующим количеством.

говорят, что если пользователь не установит флажок, он не будет добавлять ингредиент.

плато миграции

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePlatosTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('platos', function (Blueprint $table) {
            $table->increments('id');
            $table->char('nombre',50);
            $table->double('valor', 8, 2);
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('platos');
    }
}

platoController

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Plato;
use App\Ingrediente;
use App\PlatoIngrediente;


class PlatoController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
    $platos = Plato::all();


    return view('platos/index', compact('platos'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('platos/create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validatedData = $request->validate([
            'nombre' => 'required|max:50',
            'valor' => 'required|max:50'
        ]);
        $plato = Plato::create($validatedData);

        return redirect('/platos')->with('success','El Plato se guardó correctamente en la base de datos');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $plato = Plato::findOrFail($id);

        return view('platos/edit', compact('plato'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $validatedData = $request->validate([
            'nombre' => 'required|max:50',
            'valor' => 'required|numeric'
        ]);
        Plato::whereId($id)->update($validatedData);

        return redirect('/platos')->with('success', 'El Plato se actualizó correctamente en la base de datos');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $plato = Plato::findOrFail($id);
        $plato->delete();

        return redirect('/platos')->with('success', 'El Palto se eliminó correctamente en la base de datos');
    }
}

миграция platoIngrediente

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePlatosTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('platos', function (Blueprint $table) {
            $table->increments('id');
            $table->char('nombre',50);
            $table->double('valor', 8, 2);
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('platos');
    }
}

контроллер platoIngrediente

<?php

namespace App\Http\Controllers;

use App\PlatoIngrediente;
use App\Plato;
use App\Ingrediente;
use Illuminate\Http\Request;

class PlatoIngredienteController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $platos = Plato::all();
    return view('platoingrediente/index', compact('platos'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $platos = Plato::all();
        $ingredientes = Ingrediente::all();
        return view('platoingrediente/create', compact('platos','ingredientes'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
      $validatedData = $request->validate([
          'nombre' => 'required|max:50',
          'valor' => 'required|max:50',
      ]);




        $validatedData2 = $request->validate([
          'id_plato' => 'required|max:50',
          'id_ingrediente' => 'required|max:50',
          'cantidad' => 'required|max:50'
        ]);

        $plato = Plato::create($validatedData);
      $ingrediente = Ingrediente::Create($validateData2);

      return redirect('/platos')->with('success','El Plato se guardó correctamente en la base de datos');
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\PlatoIngrediente  $platoIngrediente
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\PlatoIngrediente  $platoIngrediente
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\PlatoIngrediente  $platoIngrediente
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\PlatoIngrediente  $platoIngrediente
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}

и представление platoingrediente / create

@extends('layouts.app')

@section('content')

<script>
          function showContent(el) {
          var element = el.parentNode.parentNode.nextElementSibling.querySelector('.dv');
          if (el.checked) {
            element.style.display='block';
          }
          else {
            element.style.display='none';
          }
          }
</script>


<div class="up sombra card">
  <div class="card-header">
    Creacion del plato
  </div>
  <div class="card-body">
    <div class="up">
  @if(session()->get('success'))
    <div class="alert alert-success">
      {{ session()->get('success') }}
    </div><br />
  @endif



  <dd>Primero selecciona un plato en el sistema: </dd>
  <select name="" class="form-control">
  <option selected>[ SELECCIONA UN PLATO ]</option>
   @foreach( $platos as $plato )
  <option value="{{ $plato->id }}">{{ $plato->nombre }}</option>
 @endforeach
</select>


    <div class="text-center up">
      <label class="name">  Agregar Ingredientes a el plato </label>
  </div>

<table class="table table-striped">
  <thead>
    <tr>
      <td>ID</td>
      <td>Nombre del Ingrediente</td>
      <td>Proveedor</td>
      <td>Agregar</td>
      <td>Cantidad</td>
    </tr>
  </thead>
  <tbody>
      @foreach($ingredientes as $ingrediente)
      <tr>
          <td>{{$ingrediente->id}}</td>
          <td>{{$ingrediente->nombre}}</td>
          <td>{{$ingrediente->proveedor}}</td>
          <td>

              <label>
            <input type="checkbox" name="check" id="check" value="" onchange="javascript:showContent(this)" />
          </label>

          </td>
          <td>
            <div class="form-group row">
             <div class="col-sm-4">
               <div class="dv" style="display:none;">
            <input class="dvs" type="number" />
            </div>
          </div>
          </div>
          </td>
      </tr>
      @endforeach
  </tbody>
</table>


</div>


</div>
</div>
@endsection

если вам нужна дополнительная информация, такая как модели, пожалуйста, прокомментируйте, если вам нужно больше объяснений, также прокомментируйте!

1 Ответ

0 голосов
/ 21 мая 2019

Создайте взаимосвязь между многими блюдами (Платон) и ингредиентами (Ingrediente) (многие блюда могут содержать много ингредиентов).

Ниже предполагается, что у вас есть модель для Ингредиента и Платона

создать сводную таблицу:

public function up()
    {
        Schema::create('plato_ingrediente', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('plato_id')->unsigned();
            $table->integer('ingrediente_id')->unsigned();
        });
    }

Добавить отношения к моделям:

Платон Модель:

public function ingredientes()
{
    return $this->belongsToMany('App\Plato');
}

Ингредиент Модель

public function platos()
    {
        return $this->belongsToMany('App\Ingrediente');
    }

Используя входные данные из флажка с идентификатором ингридиента в качестве значения, добавьте ингредиент к плато:

$plato = Plato::find($id);
$plato->ingredientes()->attach($ingrediente_id);

Получить ингредиенты из Платона:

$plato = Plato::find($id);
$ingredientes = $plato->ingredientes //returns a collection of ingredientes
$foreach($ingredientes as $ingrediente)
{
    //do something e.g.
    echo $ingrediente->id;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...