Eloquent Relationship / Laravel Onetomany

Asked

Viewed 447 times

0

Good afternoon, I am using Laravel 5.7 to create an order system. Therefore I have 3 tables: customers, products and orders.

My Database: inserir a descrição da imagem aqui

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();

  • @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();

  • @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;
 }

  • would be @foreach @endforeach

  • 2

1 answer

0

Thanks @adventistaam

The problem of VIEW and relationships were solved. Now I’ll get the creates and updates!

Model Pedido

public function clientes()
{
    return $this->belongsToMany('App\Cliente', 'pedidos', 'cliente_id', 'id');
}

public function produtos()
  {
      return $this->belongsToMany('App\Produto', 'pedidos', 'produto_id', 'id');
  }

Customer and Product Model

public function pedidos()
{
  return $this->belongsToMany(Pedido::class);
}

View index

 @foreach ($pedidos as $pedido)
                <tr>
                  <td >{{ $pedido->id }}</td>
                  <td >{{ $pedido->clientes[0]->nome_completo }}</td>
                  <td >{{ $pedido->clientes[0]->rua }}, {{ $pedido->clientes[0]->numero }} - {{ $pedido->clientes[0]->bairro }} </td>
                  <td>{{ $pedido->produtos[0]->nome }}</td>
                  <td>{{ $pedido->quantidade }}</td>
                  <td>{{ $pedido->produtos[0]->valor }}</td>
                  <td>{{ date('d/m/Y H:i', strtotime($pedido->created_at)) }}</td>
                  <td> @if ($pedido->pago == 1)
                    Pago
                  @else
                    Débito
                  @endif</td>
                  <td>
                    <ul class="list-inline list-small">
                          <li class="list-inline-item"><a title="Editar" href="{{ route('pedidos.edit', ['pedido' => $pedido->id]) }}" class="btn btn-warning btn-sm"><span class="fas fa-edit"></span></a></li>
                          <li title="Excluir" class="list-inline-item">
                            <form  action="{{ route('pedidos.destroy', ['pedido' => $pedido->id]) }}" onsubmit="return confirm('\nTem certeza que deseja excluir esta nota?'); return false;" method="post">
                              {{ csrf_field() }}
                              {{ method_field('DELETE') }}
                            <button type="submit" class="btn btn-danger btn-sm"><span class="fas fa-trash-alt "></span></button>
                          </form>
                        </li>
                    </ul>
                  </td>
                </tr>
              @endforeach
  • In fact, I usually popular,and prepare these actions all by jquery

Browser other questions tagged

You are not signed in. Login or sign up in order to post.