Three main tables:
products
advertisers
locations
Two pivot tables:
advertisers_locations
products_locations
Relationships:
A product belongs to an advertiser and an advertiser has many locations (Locations it can ship products to)
A product can also have it own set of locations that override the advertiser locations (Some products have delivery restrictions)
What I need to do is:
-
Select all products
-
Check if products_locations table for product ID and join it.
-
If it does not exist then join the advertisers locations table
Is this possible to do in one query and using eloquent? Here's my code - struggling with the conditional:
public function scopeWhereShippableToLocation($query)
{
$location_id = session('location_id');
$query = $query->join('products_locations', function ($q) use ($location_id) {
$q->on('products_locations.product_id', '=', 'products.id')
->where('products_locations.location_id', '=', $location_id);
});
$query = $query->join('advertisers_locations', function ($q) use ($location_id) {
$q->on('advertisers_locations.advertiser_id', '=', 'products.advertiser_id')
->where('advertisers_locations.location_id', '=', $location_id);
});
return $query;
}
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire