TL:DR
城市模型 - 地点模型 - 提供模型。 1个城市有许多地点,地点属于ToMany提供的
City::with('locations.offers')->where('slug','=', $city)->first();
显示来自关系的0个优惠,即使有连接到位置的优惠记录(连接到城市)。
更长的版本:
我有3个型号应该相互连接。城市,位置&报价。
我拥有指定的城市,并希望检索所有与城市相关的优惠地点。在输出中:
City::with('locations.offers')->where('slug','=', $city)->first();
我看到城市和所有与城市相关的位置。每个位置都有一个空的报价关系。
模范城市:
class City extends Model
{
public function locations()
{
return $this->hasMany('App\Location');
}
}
模型位置
class Location extends Model
{
public function city()
{
return $this->belongsTo('App\City');
}
public function offers()
{
return $this->belongsToMany('App\Offer','location_offer','offer_id','location_id');
}
}
模特优惠
class Offer extends Model
{
public function locations()
{
return $this->belongsToMany('App\Location','location_offer','offer_id','location_id');
}
}
数据库非常基础:
显然,我做错了什么,但似乎无法弄明白。任何提示将不胜感激。
答案 0 :(得分:1)
您的代码很完美,您的关系中存在一个小错误
public function offers()
{
return $this->belongsToMany('App\Entities\Offers','location_offer','location_id','offer_id');
}
您需要检查此link第三个参数是错误的
第三个参数是您定义关系的模型的外键名称,而第四个参数是您要加入的模型的外键名称:
检查查询
这是您的代码将执行的
select `offer`.*, `location_offer`.`offer_id` as `pivot_offer_id`, `location_offer`.`location_id` as `pivot_location_id` from `offer` inner join `location_offer` on `offer`.`id` = `location_offer`.`location_id` where `location_offer`.`offer_id` in ('1', '2')
看到连接错误:
加入location_offer
上的offer
。id
= location_offer
。location_id
这是正确的
select `offer`.*, `location_offer`.`location_id` as `pivot_location_id`, `location_offer`.`offer_id` as `pivot_offer_id` from `offer` inner join `location_offer` on `offer`.`id` = `location_offer`.`offer_id` where `location_offer`.`location_id` in ('1', '2')
加入location_offer
上的offer
。id
= location_offer
。offer_id