Use find field returned to add more results in the same query

Asked

Viewed 47 times

1

In the code below I look for a product and take the field "related" it to make a search in the bank bringing all the products (including himself) that have the same value in this field.

It is possible to do all this with just one query instead of two?

$produto = Produto::find(7996);

$relacionados = Produto::where('relacionado', $produto->relacionado)->get();
  • Can make a subQuery for the search of produto->relacionado? that would be it?

  • That. How could I pass the value of the "related" field of the product found in find to that subquery?

1 answer

1


If you can use the whereRaw to write a Sub Query as follows:

$subQuery = 'relacionado = (SELECT relacionado FROM produto WHERE id=? limit 1)';
Produto::whereRaw($subQuery, array(7996))->get();

would then be a SQL but having a SubQuery for the search of the field relacionado.

The way you did it is not wrong only is it wrong to bring all fields that are not required for the second search, an optimization:

$result = Produto::where('id', 7996)->select('relacionado')->first(); // otimizado
$relacionados = Produto::where('relacionado', $result->relacionado)->get();

A summary of the code can be done as explained in this question, with Query Scope as follows:

Create a method in your class Produto:

public function scopeRelacionado($query, $id)
{
    $subQuery = 'relacionado = (SELECT relacionado FROM produto WHERE id=? limit 1)';
    return $query::whereRaw($subQuery, array($id))->get();
}

and use as follows:

Produto::relacionado(7996);

Browser other questions tagged

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