1

Tenho as seguintes tabelas do meu sistema, products, provider e product_provider, possuem as seguintes estruturas:

Schema::create('products', function(Blueprint $table)
    {
        $table->increments('id');
        $table->string('code_1');
        $table->string('code_2')->nullable();
        $table->string('code_3')->nullable();
        $table->string('ean')->nullable();
        $table->string('location');
        $table->text('name', 65535);
        $table->text('aplications', 65535)->nullable();
        $table->string('image')->nullable();
        $table->decimal('value_cost');
        $table->decimal('percentage_addition');
        $table->decimal('value_sale');
        $table->decimal('stock_minimum')->nullable();
        $table->decimal('stock_maximum')->nullable();
        $table->decimal('stock');
        $table->decimal('quantity_sold');
        $table->boolean('notifications_minimum');
        $table->boolean('notifications_zero');
        $table->integer('brand_id')->unsigned()->index('products_brand_id_foreign');
        $table->integer('category_id')->unsigned()->index('products_category_id_foreign');
        $table->integer('status_id')->unsigned()->index('products_status_id_foreign');
        $table->integer('unit_id')->unsigned()->index('products_unit_id_foreign');
        $table->integer('warranty_id')->unsigned()->index('products_warranty_id_foreign');
        $table->timestamps();
    });

Schema::create('providers', function(Blueprint $table)
    {
        $table->increments('id');
        $table->string('social_reason');
        $table->string('fantasy_name')->nullable();
        $table->string('contact');
        $table->string('cnpj');
        $table->string('state_registration')->nullable();
        $table->string('phone')->nullable();
        $table->string('cell_phone')->nullable();
        $table->string('email')->nullable();
        $table->string('informations')->nullable();
        $table->string('address')->nullable();
        $table->string('number')->nullable();
        $table->string('neighborhood')->nullable();
        $table->string('city');
        $table->integer('state_id')->unsigned()->index('providers_state_id_foreign');
        $table->string('zip_code')->nullable();
        $table->timestamps();
    });

Schema::create('product_provider', function(Blueprint $table)
    {
        $table->increments('id');
        $table->integer('product_id')->unsigned()->index('product_provider_product_id_foreign');
        $table->integer('provider_id')->unsigned()->index('product_provider_provider_id_foreign');
        $table->decimal('value')->nullable();
        $table->timestamps();
    });

Meu model product existe a relação:

public function providers()
{
    return $this->belongsToMany(Provider::class)->withPivot(['value', 'created_at', 'updated_at']);
}

No meu controller products, tenho uma view de listagem de dados, onde quero filtrar pelo "provider_id", tenho o seguinte código que crio a aplicação da condição no SQL, exemplo:

if($filter_code){
        $filter_all[] = ['code_1', '=', $filter_code];
    }
    if($filter_status){
        $filter_all[] = ['status_id', '=', $filter_status];
    }

Minha consulta:

$products = $this->product::where($filter_all)->orderBy('name')->with('category', 'status', 'providers')->paginate($this->total_page);

Eu recebo o provider_id da consulta da view, mas como faço para incluir ele na condição do SQL, pois se trata de um valor que esta na tabela de relacionamento.

5
  • qual SQL você precisa executar?
    – novic
    24/06/2018 às 1:06
  • Para esta consulta $products = $this->product::where($filter_all)->orderBy('name')->with('category', 'status', 'providers')->paginate($this->total_page); as condições só equivalem para a tabela produtos, eu quero uma condição tipo, provider_id = 1, mas eu não tenho esse campo na tabela products, esta na product_provider 24/06/2018 às 13:58
  • Faz um join aí terá o campo no where.!
    – novic
    24/06/2018 às 14:17
  • Imaginei que teria que fazer assim, mas não sei como fazer, tem um exemplo pra mim? 24/06/2018 às 14:54
  • Coloquei uma resposta! acho que seria isso.
    – novic
    24/06/2018 às 14:55

1 Resposta 1

1

Para funcionar, precisa chegar na tabela product_provider com um join e fazendo relação com a tabela produto, e posteriormente um filtro where do campo provider_id, exemplo:

$this->product::where($filter_all)
    ->join('product_provider', 'product_provider.product_id','=','produto.id')
    ->where('product_provider.provider_id',$value_provider_id) 
    ->orderBy('produto.name')
    ->with('category', 'status', 'providers')
    ->paginate($this->total_page);

a variável $value_provider_id é aquela relatada nos comentários que vem da sua view.

Referencia: Laravel - Queries#joins

1
  • 1
    Perfeito, funcionou, muito obrigado pela ajuda. 24/06/2018 às 15:10

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .