jeudi 13 juillet 2017

How can I retrieve the information I want using MySQL `joins` or Laravel `relationships`?

I am working on a project using the Laravel framework. In this project I have three tables:


1) Master Part Numbers (master_part_numbers)

Columns: id, part_number

Values: 1, MS26778-042


2) Inventory (inventory)

Columns: id, master_part_number, stock_qty

Values: 1, 1, 7


3) Inventory Min Maxes (inventory_min_maxes)

Columns: id, master_part_number, min_qty

Values: 1, 1, 10


I am trying to find the inventory where the stock level is below the min_qty. I have been attempting this using joins, like so:

$test = MasterPartNumber::table('master_part_numbers')
                            ->join('inventory', 'master_part_numbers.id', '=', 'inventory.master_part_number_id')
                            ->join('inventory_min_maxes', 'master_part_numbers.id', '=', 'inventory_min_maxes.master_part_number_id')
                            ->select('master_part_numbers.part_number')
                            ->where('inventory.stock_qty', '<=', 'inventory_min_maxes.min_qty')
                            ->get();

However I am getting an empty collection every time. I have tried removing the where() clause and I get all the part numbers in the inventory, so it feels like I'm on the right track, but missing a critical component.

Also, I don't know if there is an easier or more efficient way to do this using Laravel's Eloquent Relationships, but that option is available.

Note: I added the space after table('master_part_numbers') in my query displayed here on purpose, for readability.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire