Return columns from belongsToMany Laravel pivot table

Asked

Viewed 672 times

2

inserir a descrição da imagem aqui

Good morning person.

I created a search that returns requests and when I click opens the products of that request. However I cannot make the products appear as a string, only in array format as in the image. Anyone knows what I have done wrong?

MODEL REQUEST

public function produto()
{
    return $this->belongsToMany(Produto::class,'solicitacaodet');
}

PRODUCT MODEL

public function solicitacao()
{
    return $this->belongsToMany(Solicitacao::class,'solicitacaodet');
}

CONTROLLHER

public function create(){
  //    if(Gate::denies('equipamento-create')){       
  //    return view('admin._msg');
  // }
  $solicitacoes = Solicitacao::All();      

  $pessoas=DB::table('pessoasolcompvend')
    ->where('solicitante', '=', 's')
    ->orderby('pessoa')
    ->get();

  $unidades=DB::table('unidadeadm')       
  ->orderby('unidadeadm')
  ->get();

  $localentrega=DB::table('localentrega')           
  ->orderby('localentrega','asc')
  ->get();



    $caminhos = [
      ['url'=>'/home','titulo'=>'Inicio'],
      ['url'=>route('pedidocompra.index'),'titulo'=>'Pedido de Compra'],
      ['url'=>'','titulo'=>'Create'],
  ];
   return view('compra.pedidocompra.create',compact('solicitacoes','detalhes','pessoas','unidades','localentrega','produtos','centrocustos','caminhos'));
 }

VIEW

Solicitation Date

      <?php foreach ($solicitacoes as $solicitacao){?>
        <tr style="background-color: #e1e1e1;color: black">                
            <td id="id"><a href="#"><?php echo $solicitacao->idsolicitacao?></a></td>   
            <td><?php echo date('d/m/Y', strtotime($solicitacao->data))?></td>
        </tr>

            <tr>
                <td colspan="2">

                    <table class="table table-striped table-bordered">
                       <thead>
                        <tr>
                          <th></th>
                          <th>Id</th>
                          <th>Produto</th>
                          <th>Qnt</th>                
                          <th>Detalhe</th>                
                        </tr>
                      </thead>
                      <tbody>
                      <?php 

                      $detalhes = $solicitacao->solicitacaodet;
                      $produtos = $solicitacao->produto;                          
                      $centrocusto = $solicitacao->centrocusto;


                      ?>                   

                      <?php foreach ($detalhes as $detalhe){?>                          
                      <tr>
                        <td>
                          <input type="checkbox" />
                        </td>
                        <td><?php echo $detalhe->produto_idproduto ?></td>
                        <td>
                          <?php 

                              echo $detalhe->produto()->select('produto')->get();
                              // echo $produto->produto

                          ?>                                
                        </td>
                        <td><?php echo $detalhe->qnt ?></td>                           
                        <td><?php echo $detalhe->detalhe ?></td>                           
                      </tr>
                       <?php } ?> 
                    </tbody>                        
                    </table>                        
                </td>
            </tr>

        <?php } ?>           
    </tbody>
    </table>      



</div>              
  • I don’t understand, if you already get the products picking up $products = $request->product; why do you foreach in detail? and still get a get at the end?? echo $detail->product()->select('product')->get(); making a foreach on $products, would already bring one product at a time, and remember that ->get() will always return a collection to you

  • solicitacaodet and pivot table. In it will idproduct/idcentrocusto(foreign keys) + qnt + product details, however I am not able to show the product description and cost center only ids. Ex I do a foreach of details and I do not bring description poduto, or I do foreach product and I can not bring the data requecaodet.

  • This is how it returns - > [{"PRODUCT":"DUMMY CABLE SET"}].

  • but then you have to pass the pivot table and the pivot fields on the relation, something like this: public Function request() { Return $this->belongsToMany(Request::class,'requecaodet')->withPivot('qnt','details'); } and then you foreach with products, and when you want to print the pivot fields you do so: $product->pivot->qnt

  • I am trying but this giving error. Use pivot only in Request or solicitacaodet too? I’m not sure how to mount..

  • I’ll post it as an answer, see if it gets clearer

Show 1 more comment

2 answers

3


In Laravel, to access a value present in a Pivot table it is necessary to use the attribute pivot.

For example, if you have a relationship N:N of Usuario for Produto, you would have three tables: usuarios, produtos and usuarios_produtos, where usuarios_produtos has the columns produto_id, usuario_id and preco

You would need to set the relationship in the table Usuario thus:

// bastante atenção no plural em caso de relacionamentos que têm mais de um retorno
public function produtos()
{
      return $this->belongsToMany(Produto::class, 'usuarios_produtos')->withPivot(['preco']);
}

Note that it is necessary to call withPivot to include "extra columns" of the relationship table N:N.

Now, just call on the view like this:

   @foreach($usuarios as $usuario)
    O usuário {{ $usuario->nome }} tem os seguintes produtos:

    @foreach($usuario->produtos as $produto)
        O produto é {{ $produto->nome }} e o preço é {{ $produto->pivot->preco }}
    @endforeach

   @endforeach

Note that to access preco, which is not in the product table, but in usuarios_produtos, it was necessary to call the property pivot, because it contains the elements connecting the two tables.

  • And in my case I have relationship with 3 tables Request -> (pivo=solicitacaodet) <-within it goes Product and Cost Center. How would it be

  • Thank you very much, it worked however lacked the third table to implement that in case would be cost center

0

MODEL REQUEST (check if the fields in whitPivot are right with your link table)

public function produto()
{
    return $this->belongsToMany(Produto::class,'solicitacaodet')->whitPivot('qnt','detalhe');
}

CONTROLLHER

$solicitacoes = Solicitacao::All();   

VIEW

$produtos = $solicitacao->produto;  

foreach($produtos as $produto){
  echo $produto->pivot->detalhe;
}
  • Thank you very much, it worked but lacked the third table to implement that in the case would be cost center -

  • I don’t understand, the third table, but just create it in the model too, and access through the function, same as the others, only be in the pivot table, just add the fields, if it worked, please, a positive vote and as solved

  • Sorry I’m new here,to vote and just give up really? And to finish how I do?

  • Yes to vote is arrow up, including in the comments, and to finish, you choose the answer, and mark as accepted!

Browser other questions tagged

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