Laravel - Where in relationships?

Asked

Viewed 95 times

0

I have a function that looks for a value of a query with WHERE in relationship :

$em = \App\Elevatoria::whereHas('elevatorias_monitoramento', function(Builder $query) {
    $query->where('elevm_elevatoria_configuracoes_id', '=', 1);
})->get();

And then she uses the result of $em in another consultation, only from another bank (ODBC):

try {

  \Config::set('database.connections.testeConnection', $r);

  $elevatorias = [];
  foreach ($em as $key => $value) {
    $statement = DB::connection('testeConnection')
       ->getPdo()
       ->prepare(str_replace("***".$ec->elev_troca_sql."***",
          $value->elevm_nome, $ec->elev_db_sql_monit)
       );

    $statement->execute();

    $elevatorias[] = array_merge(
        array_change_key_case($value->elevatoria->toArray(), CASE_UPPER), 
        $statement->fetchAll(\PDO::FETCH_ASSOC)[0]);
}

return Response::json($elevatorias, 200);

} catch (\Exception $e) {
  return $this->responseReturn(array(
        'return'  => 'error', 
        'type'    => 'not_connection', 
        'titulo'  => 'Ops, deu ruim!', 
        'message' => 'Não foi possível realizar a conexão!',
        'system_message' => $e->getMessage()
  ), 500);
}

But it’s giving error, as if the first query of WHERE in the relationship was using the new settings ODBC, but it is not. The error is as follows:

odbc_execute(): SQL error: [Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near the keyword 'WHERE'., SQL state 37000 in SQLExecute

Funny, that if I leave the query as below, it works, but can not do the WHERE that I need.

$em = \App\Elevatoria_monitoramento::with(['elevatoria'])
       ->where('elevm_elevatoria_configuracoes_id', '=', $ec->id)
       ->get();

Follow the full code:

public function buscaValores(Request $request)
{
    //Verifica se usuário tem autorização
    if(!Auth::user()->can('elevatoria-monitoramento-show'))
    {
        Log::alert('Usuário ' . Auth::user()->u_nome . ' sem acesso para buscar ad informações da página elevatoria');
        return $this->returnNoAccess('visualizar');
    }

    $u = Auth::user()->hasRole('super-admin');
    if($u){
        $ec = \App\Elevatoria_configuracoes::where('entidade_id', '=', Auth::user()->id)->first();
        //$em = \App\Elevatoria_monitoramento::with(['elevatoria'])->where('elevm_elevatoria_configuracoes_id', '=', $ec->id)->get();
        $ecid = $ec->id;

        $em = \App\Elevatoria::whereHas('elevatorias_monitoramento', function(Builder $query) use ($ecid) {
            $query->where('elevm_elevatoria_configuracoes_id', '=', $ecid);
        })->get();

    }else{
        //Pega o id da entidade_id
        $e  = Auth::user()->entidade_id;
        //
        $p = \App\Elevatoria::where('elev_ativo', 1)->where('entidade_id', $e)->get();
    }

    try{
        $c = \App\Conexao::where('id', '=', $ec->conexao_id)->first();
        $c->ec = 1;

        $ta = '\Illuminate\Http\Request';
        $r = \App::make(
            '\App\Http\Controllers\ConexaoController'
            )->callAction(
                'testeConexaoes', [
                'value' => $ta::create('ConexaoController', 'POST', $c->toArray())
            ]);

        if(($c->cx_tipo != 'soap') && ($c->cx_tipo != 'restful'))
        {

            try {
                \Config::set('database.connections.testeConnection', $r);

                $elevatorias = [];
                foreach ($em as $key => $value) {
                    $statement = DB::connection('testeConnection')->getPdo()->prepare(str_replace("***".$ec->elev_troca_sql."***", $value->elevm_nome, $ec->elev_db_sql_monit));

                    $statement->execute();

                    $elevatorias[] = array_merge(
                        array_change_key_case($value->elevatoria->toArray(), CASE_UPPER), 
                        $statement->fetchAll(\PDO::FETCH_ASSOC)[0]);
                }

                return Response::json($elevatorias, 200);

            } catch (\Exception $e) {
                return $this->responseReturn(array(
                    'return'  => 'error', 
                    'type'    => 'not_connection', 
                    'titulo'  => 'Ops, deu ruim!', 
                    'message' => 'Não foi possível realizar a conexão!',
                    'system_message' => $e->getMessage()
                ), 500);
            }
        }elseif($c->cx_tipo == 'restful'){
            $elevatorias = [];

            $r = json_decode($r->getBody()->getContents());

            if(isset($r->readResults)) {
                $a = [];
                foreach($r->readResults as $key => $value) {
                    $a[strtoupper(explode('.', $value->id)[2])] = $value->v;
                }

                foreach ($em as $key => $value) {
                    $elevatorias[] = array_merge(
                        array_change_key_case($value->elevatoria->toArray(), CASE_UPPER), 
                        array_change_key_case($a, CASE_UPPER));
                }
            }

            return Response::json($elevatorias, 200);
        }

    }catch(\Exception $e){
        return $this->responseReturn(
            array(
                'return'  => 'error', 
                'type'    => 'not_updated', 
                'titulo'  => 'Ops, deu ruim!', 
                'message' => 'Não foi possível buscar as informações das elevatórias!',
                'system_message' => $e->getMessage()
        ), 500);
    }
}
  • What’s in that variable: $ec->elev_troca_sql?

  • I receive a string containing an SQL. Type: "SELECT * FROM ***NAME***WHERE..." Here ***NAME**I replace it with another value. It’s supposed to be a dynamic consultation.

  • 1

    must be missing a space in the type substitution in replace pass with a space in the beginning and end type str_replace($ec->elev_troca_sql,' '.$value->elevm_nome.' ',$ec->elev_db_sql_monit); check if that’s it, because you had to have debugged that replace.

  • So @Virgilionovic, funny that when I use this code: $em = App Elevatoria::whereHas('elevatorias_monitoring', Function(Builder $query) { $query->Where('elevm_elevatoria_configuracoes_id', '=', 1); })->get(); Gives the error reported, but when I use this: $em = App Elevatoria_monitoring::with(['elevatoria']) ->Where('elevm_elevatoria_id', '=', $Ec->id) ->get(); No error. But the return of the two ($Ec->elev_troca_sql) is the same. There is no difference in this variable. I believe this is not the problem

  • I think I understand what you mean. Perai, do a var_dumps here to check. Hold on there

  • There are problems maybe in the relationship, so it is difficult to debug! if you have to do this by yourself line the line of this method

  • 1

    So that was the problem right there! Thank you @Virgilionovic. In one query I was looking for a table and in the other query for another. The problem was named after the variable: str_replace($Ec->elev_troca_sql,' '.$value-> elevm_name .' ',$Ec->elev_db_sql_monit); Thank you so much for your help!!

Show 2 more comments

1 answer

2

Your Where is wrong, only uses operator when using Whereraw, if use only Where can pass like this:

$em = \App\Elevatoria_monitoramento::with('elevatoria')
       ->where('elevm_elevatoria_configuracoes_id', $ec->id)
       ->get();

Browser other questions tagged

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