Ich habe eine Abfrage, die ich versuche, abzurufen. Es soll eine Auflistung von Informationen mit seinen Reisen und Standortdetails erhalten. DieseJoin zu linken Abfragen in Laravel
ist wie Im die Abfrage innerhalb der Ziele Controller Aufruf:
public function destinations($id) {
$destination = Destination::findOrFail($id);
$listingGuides = Listing::findGuidesTrips($destination)
->with('locations')
->withCount('trips')
->get();
return view('destinations.index', compact('listingGuides');
}
Und die findGuidesTrips
Methode ist innerhalb des Listings Modell:
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;
}
Das ist das, was ich zurück:
Wie Sie c ein see, ich habe 2 $ query = self :: query() quires, aber nur einer wird aufgerufen (der untere). Es ignoriert die oberste self :: query.
Ich fragte mich nur, wie ich diese 2 leftJoin Abfragen in eine vielleicht kombinieren würde? Oder gibt es eine bessere Möglichkeit, diese Abfrage durchzuführen?
(Ich habe versucht, dies zu tun:)
$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');
Aber es gibt mir Integrity constraint violation: 1052 Column 'listing_id' in on clause is ambiguous
Fehler
Auf einen Blick, beachten Sie nur, dass Sie den Namen der Tabelle auf 'angeben -> leftJoin()' Funktionen, wie '-> leftJoin ('Ausflüge', ' trips.listing_id ',' = ',' listings.id ') 'oder' -> leftJoin (' locations ',' locations.listing_id ',' = ',' listings.id ') '; Das würde dein Mehrdeutigkeits-Problem beseitigen. –
Versuchen Sie 'trips.listing_id' für die erste und' locations.listing_id' für die zweite anstelle von 'listing_id' in der letzten Abfrage. – C2486
@TimLewis Netter Job Mann, habe nicht darüber nachgedacht. Ja, das bringt genau das zurück, was ich wollte! Vielen Dank. – David