How to group data from a related table in Laravel?

2

I want to group the records that have more than one related record. Example:

I have a table called assignments and another table called sales, so an assignment can have a lot of sales. In the table assignments I have 2 records and in sales I have 3,

ventas                            asignaciones
id | asignacion_id                id | user_id
---|---------------               ---|---------
1  | 1                            1  | 1
2  | 1                            2  | 2 
3  | 2 

I made the following query.

$asignaciones = DB::table('asignaciones')
                    ->select('asignaciones.*')
                    ->join('ventas', 'ventas.asignacion_id', '=', 'asignaciones.id')
                    ->where('asignaciones.estado','1')
                    ->whereBetween('asignaciones.created_at', array($fecha_1, $fecha_2))
                    ->get();

And show me this:

I see a duplicate data, is there any way to group it?

    
asked by Marcial Cahuaya Tarqui 08.03.2017 в 14:38
source

1 answer

1

to bring the different assignments it would be enough to make use of distinct .

$asignaciones = DB::table('asignaciones')
                ->select('asignaciones.*')
                ->distinct() // <== Con esto traes solo las asignaciones que son distintas en el corpus de datos
                ->join('ventas', 'ventas.asignacion_id', '=', 'asignaciones.id')
                ->where('asignaciones.estado','1')
                ->whereBetween('asignaciones.created_at', array($fecha_1, $fecha_2))
                ->get();
    
answered by 08.03.2017 в 16:30