三个主要表:
产品
广告商
位置
两个枢轴表:
advertisers_locations
products_locations
关系:
产品属于广告商,广告商有许多位置(可以将产品运送到(
(产品还可以拥有自己的一组位置来覆盖广告商位置(某些产品具有交付限制(
我需要做的是:
选择所有产品
检查产品ID的products_locations表格并加入它。
如果不存在,请加入广告商位置表
这可以在一个查询中进行并使用雄辩吗?这是我的代码 - 在条件下挣扎:
public function scopeWhereShippableToLocation($query)
{
$location_id = session('location_id');
$query->where(function ($q) use ($location_id) {
$q->join('products_locations', 'products_locations.product_id', '=', 'products.id')
->where('products_locations.location_id', '=', $location_id);
});
$query->orWhere(function ($q) use ($location_id) {
$q->join('advertisers_locations', 'advertisers_locations.advertiser_id', '=', 'products.advertiser_id')
->where('advertisers_locations.location_id', '=', $location_id);
});
//dd($q->toSql());
return $query;
}
这当前正在产生一个mysql错误:
Column not found: 1054 Unknown column 'products_locations.location_id' in 'where clause' (SQL: select `products`.*,
我想我有一个解决方案,可以使用雄辩而不是查询构建器。您需要检查是否存在关系,如果不存在,则需要其他查询。可以使用以下内容完成:
public function scopeWhereShippableToLocation($query)
{
$location_id = session('location_id');
// WhereHas check to see if a relationship exists, IE: The pivot table
// orWhereHas will be checked if the first where does not exist
$query->whereHas('products_locations', function ($q) use ($location_id) {
$q->where('location_id', $location_id);
})->orWhereHas('advertisers_locations', function ($q) use ($location_id) {
$q->where('location_id', $location_id);
});
return $query;
}
这应该有效,以设置您的Products
,Advertisers
和Locations
关系方法。