Eloquent with does not do inner join?

1

I remember the old "find" that in a query using Eloquent, if I used with Laravel made a inner join .

Today I happened to check the queries of a project and ...

[2014-11-20 23:21:16] sql.INFO: select * from 'ocurrences' where 'ocurrences'.'deleted_at' is null order by RAND() limit 4 {"bindings":[],"time":3.58,"name":"mysql"} []
[2014-11-20 23:21:16] sql.INFO: select * from 'users' where 'users'.'id' in ('7') {"bindings":["7"],"time":0.49,"name":"mysql"} []
[2014-11-20 23:21:16] sql.INFO: select * from 'users' where 'users'.'id' = '7' limit 1 {"bindings":["7"],"time":0.51,"name":"mysql"} []
[2014-11-20 23:21:16] sql.INFO: select * from 'tags' limit 5 {"bindings":[],"time":0.41,"name":"mysql"} []

In this case, I'm doing the query this way:

/**
 * Get random ocurrences for home
 * @return mixed
 */
public static function randomForHome()
{
  return static::with('user')
    ->orderByRaw('RAND()')
    ->limit(4)
    ->get();
}

What's wrong and / or how do I do with Eloquent joins?

    
asked by anonymous 21.11.2014 / 00:35

3 answers

4

I needed to use the join() method of Eloquent. Initially I thought that with was playing joins too, but by the way not anymore.

So I had to change the with to: join('users', 'users.id', '=', 'ocurrences.user_id') .

Anyway, that's it.

Here is the final solution below:

/**
 * Get random ocurrences for home
 * @return Eloquent
 */
public static function randomForHome()
{
  return static::join('users', 'users.id', '=', 'ocurrences.user_id')
    ->orderByRaw('RAND()')
    ->limit(4)
    ->get();
}
    
21.11.2014 / 00:58
1

It can also be done this way.

DB::table('TABELA')
->join('TABELA2', 'CODIGO.TABELA1', '=', 'CODIGO.TABELA2')
->where('1 = 1')
->get();
    
11.09.2015 / 21:37
0

Everyone has this question regarding the "why not use join" of eloquent, well, I'm not much inside either ... but I really believe it's because of performance or ambiguity.

When using with it will execute the query from the parent and run a second query to retrieve all children from relationships, while retaining integrity.

$pedidos = $pedidos
    ->select('id', 'id_pedido', 'hora_pedido', 'local_venda', 'cidade', 'estado')
    ->with(['itens' => function($q){
            $q->where('clientes_id', \Session::get('idClienteTray'));
            $q->select('PedidosTray_id', 'id_produto', 'quantidade');

        },
        'itens.produto' => function($q)
        {
            $q->where('clientes_id', \Session::get('idClienteTray'));
            $q->select('id_produto', 'descricao');

        }])

This is the well-known method Eager loading

Here's a friend with a possible explanation: link

    
11.09.2015 / 21:24