laravel4.2 union联合,join关联分组查询最新记录时,查询条件不对,解决方案

需求: 分组联合查询,或者最新记录。 

问题:  mysql分组的时候默认会查询第一条记录,存在gourp by时 order by 无效。 一般解决办法就是 ,select * from ( select * from order by id) group by 。 因为项目实际中 查询规则复杂,需要使用到  union 联合查询, 另外和关联查询,在 laravel4.2中 如果关联join 多条件时,在union 会出现 最后的结果集不正确。问题是出现在,laravel最后生成 where 表达式时不对。

执行 最后 sql : 

SELECT
    *
FROM
    (
        (
            SELECT
                id
            FROM
                table_a
            JOIN table_b ON table_a.id = table_b.t_id (AND table_b.x_id =  1)
            WHERE
                id =2
        )
        UNION
            (
                SELECT
                    id
                FROM
                    table_c
                JOIN table_d ON table_c.id = table_d.t_id (AND table_c.x_id =  3)
                WHERE
                    id = 4
            )
    ) AS t
GROUP BY id

正确解析应该时表达式数组是  [ 1,2,3,4]  ,实际查询laravel 表达式时  结果为[ 1,1,2,3,3,4](忘记,具体是几个,但是会出现1 和 3 出现多次是真实出现的)

$model_a = DB::table( 'table_a' )->select( 'id' )->join( 'table_b' , function( $query ){
	$query->on( 'table_b.a_id' , '=' , 'table_a.id' )
	->where( 'table_b.x_id' , 1)
})->where( 'id' , 2 )->orderBy('time','desc'); 
 
$model_b = DB::table( 'table_c' )->select( 'id' )->join( 'table_d' , function( $query ){ 
    $query->on( 'table_c.c_id' , '=' , 'table_d.id' )
    ->where( 'table_c.x_id' , 3);
})
->where( 'id' , 4 )
->orderBy('time','desc');

   

$result = $model_b->union( $model_a );
$data = DB::table( DB::raw("($result->toSql() ) as t"))->mergeBindings( $result->getBindings() )->groupBy( 'id' )->get();

  

个人解决方案: 1.

      获取2个model表达式的 查询条件 $model_a->getBindings();   结果位  [1,2]

      $model_b->getBindings();   结果位  [3,4]

$data = DB::table( DB::raw("($result->toSql() ) as t"))->setBindings(array_merge($model_a->getBindings(),$model_b->getBindings())->groupBy( 'id' )->get();

      2. 使用源生sql方式解决。

    

原文地址:https://www.cnblogs.com/inkwhite/p/10266714.html