You can use whereRaw
to write 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 relacionado
field.
The way you did it is not wrong it's just wrong to bring all the 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);