jeudi 26 octobre 2017

Laravel Select SubQuery with Scope

Thank you in advance for all your help. I have come to help, on an issue, where I can not find a solution. Basically, I need to make a subquery by laravel \ Eloquent and be able to apply the scope in the subquery. So far, I have tried with both scope models, Global and Local, but with no success. I have the following case:

I have a model with the following scope:

    public function scopeParametro($query) {
    $param = $this->param();
    if (Auth::user()->perfil != null) {
        $perfil = Auth::user()->perfil;
        if ($param == 0) {
            return $query->where('empresa_id', $perfil->empresa_id);
        } else if ($param == 1) {
            return $query->where('empresa_id', 47)
                            ->where('filial_id', 31);
        } else if ($param == 2) {
            return $query->whereNull($this->getTable() . '.empresa_id')
                            ->whereNull($this->getTable() . '.filial_id');
        }
    }
}

When I call this scope, directly from a query, it works correctly, but if I apply the same scope in the subquery, it seems to me that it does not set the values:

NOTE: The Auth variable has all attributes in both cases.

Ex:

  Saldo::select(DB::raw('sum(quantidade)'))
                    ->join('enderecos', 'saldos.endereco_codigo', 'enderecos.codigo')
            ->parametro()

This works fine. This not:

   $subQuerySaldoSetor = new \Sofa\Eloquence\Subquery(
            Saldo::select(DB::raw('sum(quantidade)'))
                    ->join('enderecos', 'saldos.endereco_codigo', 'enderecos.codigo')
            ->parametro()
    );

    return Setor::whereNotNull('id')->select(['id', $subQuerySaldoSetor])->first();

t looks like the same structure, however, placed in the subquery it generates this output:

SQLSTATE[07002]: [Microsoft][ODBC Driver 11 for SQL Server]COUNT field incorrect or syntax error (SQL: select top 1 [id], (select sum(quantidade) from [saldos] inner join [enderecos] on [saldos].[endereco_codigo] = [enderecos].[codigo] where [empresa_id] = ? and [filial_id] = ?) from [setores] where [id] is not null)

All the query is correct, but the value of the variables are not set correctly NOTE: I already tried to set the falor fixamnete, to test the function, even then, without success.

It is known that the laravel subquerys, are not very good, for complex queries. Someone has gone through something like this.

Basically, I need a part of the fixed query, so I do not have to make the comparison every time, because it's a standard coding. Another alternative to solve this case, would also help.

Thank you all for your cooperation.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2xoOCTT
via IFTTT

Aucun commentaire:

Enregistrer un commentaire