Home > Blockchain >  Laravel Eloquent, How to access eloquent on 3 tables with where?
Laravel Eloquent, How to access eloquent on 3 tables with where?

Time:11-01

I have 3 tables like this below :

Items table
id | name
1  | Laptop
2  | Computer
3  | Tv

Production table
id | date
1  | 2021-10-01
2  | 2021-10-03
3  | 2021-10-30

Detail table
id | production_id| item_id |qty
1  | 1            | 1       | 5 
2  | 1            | 3       | 10
 
3  | 2            | 1       |2
4  | 2            | 2       |3
5  | 2            | 3       |23

And what I'm trying to achieve is like this :

(where Production dateBetween this date and that date)
Items       |Sum qty 
Laptop      | 7
Computer    | 3
Tv          | 33

How to do this in eloquent way ?

Should I use hasManyThrough relationship ?

Thank you for your kind help.

CodePudding user response:

Since this is concatenation problem, i would not use standard relationships for this. Instead let mysql solve this, by creating a custom query in the ORM.

The strategy is to join all the rows, group it by the name of the product. Sum the quantity and create the where condition for the dates.

$items = Item::select('name', DB::raw('SUM(details.qty) as quantity'))
    ->join('details', 'items.id', '=', 'details.item_id')
    ->join('productions', 'productions.id', '=', 'details.production_id')
    ->whereBetween('productions.date', [now()->subMonth(), now())
    ->groupBy('details.name')
    ->get();

You could loop the data like so.

foreach ($items as $item) {
    $item->name;
    $item->quantity;
} 
  • Related