0
Good afternoon, I am using Laravel 5.7 to create an order system. Therefore I have 3 tables: customers, products and orders.
For now my Migrations are like this:
Migrations:
Migration customers:
Schema::create('clientes', function (Blueprint $table) {
$table->increments('id');
$table->text('nome_completo');
$table->text('rua');
$table->text('numero');
$table->text('bairro');
$table->text('email');
$table->text('tel');
$table->text('empresa');
$table->timestamps();
});
Migration products:
Schema::create('produtos', function (Blueprint $table) {
$table->increments('id');
$table->text('nome');
$table->float('valor');
$table->timestamps();
});
Migration requests:
Schema::create('pedidos', function (Blueprint $table) {
$table->increments('id');
$table->integer('cliente_id')->unsigned();
$table->foreign('cliente_id')
->references('id')->on('clientes');
$table->integer('produto_id')->unsigned();
$table->foreign('produto_id')
->references('id')->on('produtos');
$table->integer('quantidade');
$table->float('total', 8, 2);
$table->boolean('pago');
$table->timestamps();
});
Models:
App Product
public function pedidos()
{
return $this->belongsTo(Pedidos::class);
}
App Cliente
public function pedidos()
{
return $this->belongsTo(Pedidos::class);
}
App Requests
protected $table = 'pedidos';
protected $primaryKey = 'id';
public function clientes()
{
return $this->belongsTo(Cliente::class);
}
public function produtos()
{
return $this->hasMany(Produto::class);
}
Now how would the controllers look? I would like to retrieve ALL orders! I have tried
$pedidos = Pedido::all()->produtos;
and nothing!
The table that will be displayed in the Orders view should contain the customer’s name, product name, quantity of each product and total value.
Try to use it like this
Pedido::with('produtos')->get();
– adventistaam
@adventist was just that guy. Only that after reviewing the documentation of Laravel I realized that would be Many To Many the relationship and changed my models to $this->belongsToMany and in my controller I did what you told me, but this way: $orders = Request::with('products')->with('customers')->get();
– Denis Vanoni
@adventistaam now only left to show the data in the view!! kkk
foreach ($pedidos as $pedido) {
 echo "Nome do Produto: ".$pedido->produtos->nome;
 echo "Nome do cliente: ".$pedido->clientes->nome_completo;
 }
– Denis Vanoni
would be
@foreach @endforeach
– adventistaam
Possible duplicate of How to use hasmany relationship in Laravel 5.2?
– novic