我有一个想要检索的查询。它假设获得列表信息及其旅行和位置详细信息。
这就是我在Destinations控制器中调用查询的方式:
public function destinations($id) {
$destination = Destination::findOrFail($id);
$listingGuides = Listing::findGuidesTrips($destination)
->with('locations')
->withCount('trips')
->get();
return view('destinations.index', compact('listingGuides');
}
findGuidesTrips
方法位于清单模型中:
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;
}
这就是我的回忆:
正如你所看到的,我有2 $ query = self :: query()quires,但只有一个被调用(最后一个)。它忽略了top self :: query。
我只是想知道如何将这两个leftJoin查询合并为一个?或者有更好的方法来进行此查询吗?
(我试过这样做:)。
$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');
但它给了我Integrity constraint violation: 1052 Column 'listing_id' in on clause is ambiguous
错误
答案 0 :(得分:0)
正如@Tim Lewis和@Niklesh所说,我所要做的就是:
第一次查询 trips.listing_id
,第二次查询locations.listing_id
。
以下是最终查询:
public static function findGuidesTrips($destination) {
$query = self::query()
->leftJoin('trips', 'trips.listing_id', '=', 'listings.id')
->addSelect(
\DB::raw('listings.name,listings.slug,listings.type,listings.id,MIN(trips.cost) as starting_price')
)
->leftJoin('locations', 'locations.listing_id', '=', 'listings.id')
->addSelect(
\DB::raw('locations.longitude as longitude')
)->addSelect(
\DB::raw('locations.latitude as latitude')
)->groupBy('listings.id');
$query = $query->whereHas('locations',function($query) use ($destination) {
$query->where('region', 'like', $destination->location)->orWhere('country', $destination->location);
});
return $query;
}