Relation Hasmanythrough returns empty Eloquent

Asked

Viewed 199 times

1

I am developing a sale screen and on this screen it is possible to select several products that belong to the table produtos, the structure of the tables is as follows::

vendas:
- id

produtos:
- id

vendas_produtos:
 - id
 - venda_id
 - produto_id

What I would like to do is pull all the products of certain sale that are on the table vendas_produtos, I know the relationship is of the type Hasmanythrough but when do the relation in the model the return is empty

App\Venda.php

<?php

namespace App\Pdv;

use Illuminate\Database\Eloquent\Model;

class Venda extends Model
{
    protected $guarded = [];
    protected $table = 'vendas';

    function vendedor() {
        return $this->belongsTo('App\Vendedor', 'vendedor_id');
    }

    function produtos() {
        return $this->hasManyThrough('App\Produto', 'App\Pdv\VendaProduto', 'produto_id', 'id');
    }

    function scopeInfo($query){
        return $this->with(['vendedor', 'produtos']);
    }

}

I would need to define some method also in the vendas_produtos?

2 answers

2

If you put in your sale Entity and call pass the sale id

public function produtos($id) {
        return $this->hasMany(Produtos::class, 'id', 'produto_id')->where([
            'venda_id' => $id,
        ])->get();
    }

To call:

$produtos = $objetoVendaProduto->produtos($idVenda)

1


Assuming you sell products is a pivot

You can use a Manytomany type relationship namely a "sell many products a many sales product"

Documentation in https://laravel.com/docs/5.8/eloquent-relationships#Many-to-Many

Example

function produtos() {
        return $this->belongsToMany('App\Produto', 'vendas_produtos', 'venda_id', 'produto_id') ;
    }
  • Now I just don’t understand why hasmanythrough didn’t work, or I’m confusing the logics rs

  • hasmanythrough requires an intermediate model to exist, but in its case it may not.

Browser other questions tagged

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