Laravel: fill a select with values of tables with a foreign key

1

I am having some problems when generating select fields with data in my bd, the scenario is as follows: I have 5 tables:

  • shopping cart: id, name, description, total_price
  • Car_beverages: id, beverages_id, shopping_car_id (foreigner)
  • products_extra_carro: id, products_extra_id (foreigner), car_compra_id (foreigner)
  • Drinks: id, name, price
  • products_extra: id, name, price, provider_id (foreigner)

This I add in a form in which I add several select fields using jquery with the data of the two tables beverages and products_extra , and the selected data are stored in the tables beverages_carry and productos_extra_carro respectively, adding me works perfect but when editing I need to generate the select fields that have been previously saved from the tables beverages_carro and products_extra_carro plus the data of my tables beverages and products_extra to be able to change if desired, how could these select generate? I'm starting with Laravel and this is spinning my head .. any ideas? thanks for your answers

    
asked by maudev 06.09.2016 в 05:42
source

1 answer

1

According to what you explain you must have 3 models: BeverageCar, Beverage and ShoppingPurchase

Where BebidaCarro inherits the drink (drink_id) and carpool (car_compra_id) PKs these foreign keys must be defined in your migrations as such.

Then in your Model DrinkCarro:

public function bebidas(){
 return 
$this>belongsTo(
'App\Bebida','bebidas_id')
}

public function 
carro_compra(){
 return 
 $this>belongsTo(
 'App\CarroCompra',
 'carro_compra_id')
}

Then on your controller:

public function 
 formulario(){
 $bebidas_carro = 
 Bebidas_Carro:   
 :with('bebidas',
 'carro_compra')->get(); 
 //algo general...

 //enviamos los datos a la vista
 return view('tuvista', 
 compact(
 '$bebidas_carro'));
  }

Then in your view:

for example if in this form you want to show the names of the drinks

<select>
 @foreach($bebidas_carro as $bc)
   <option value="$bc->bebidas->id"> {{ $bc->bebidas->nombre }} </option>
 @endforeach
</select>

I hope I can help you with something.

    
answered by 06.09.2016 в 18:56