I have a query that Im trying to retrieve. Its suppose to get a listings information with its trips and location details.
This is how Im calling the query inside the Destinations controller:
public function destinations($id) {
$destination = Destination::findOrFail($id);
$listingGuides = Listing::findGuidesTrips($destination)
->with('locations')
->withCount('trips')
->get();
return view('destinations.index', compact('listingGuides');
}
And the findGuidesTrips
method is inside the Listings Model:
public static function findGuidesTrips($destination) {
$query = self::query()
->leftJoin('trips', 'listing_id', '=', 'listings.id')
->addSelect(
\DB::raw('listings.name,listings.slug,listings.type,listings.id,MIN(trips.cost) as starting_price')
)
->groupBy('listings.id');
$query = self::query()
->leftJoin('locations', 'listing_id', '=', 'listings.id')
->addSelect(
\DB::raw('locations.longitude as longitude')
)->addSelect(
\DB::raw('locations.latitude as latitude')
);
$query = $query->whereHas('locations',function($query) use ($destination) {
$query->where('region', 'like', $destination->location)->orWhere('country', $destination->location);
});
return $query;
}
This is what I get back:
As you can see, I have 2 $query = self::query() quires, but only one is being called (the bottom one). Its ignoring the top self::query.
I was just wondering how would I go about combining these 2 leftJoin queries into one perhaps? Or is there a better way of doing this query?
( I tried doing this: )
$query = self::query()
->leftJoin('trips', 'listing_id', '=', 'listings.id')
->addSelect(
\DB::raw('listings.name,listings.slug,listings.type,listings.id,MIN(trips.cost) as starting_price')
)
->leftJoin('locations', 'listing_id', '=', 'listings.id')
->addSelect(
\DB::raw('locations.longitude as longitude')
)->addSelect(
\DB::raw('locations.latitude as latitude')
)->groupBy('listings.id');
But it gives me Integrity constraint violation: 1052 Column 'listing_id' in on clause is ambiguous
error
via David