我有下面的模型关系。
promotions: [id, title, description]
sectors: [id, name]
promotion_sector: [promotion_id, sector_id]class Promotion extends Model {
public function sectors() {
return $this->belongsToMany('App\Sector');
}
}我想得到某些部门的晋升机会。
例如,
A和B部门的所有促销活动
发布于 2015-05-28 05:13:09
我不知道你用的是哪种关系。我认为这是Many-To-Many的关系。
下面是您可以尝试的代码:
$result = DB::table('promotion_sector')
->join('promotions', 'id', '=', 'promotion_sector.promotion_id')
->join('sectors', 'id', '=', 'promotion_sector.sector_id')
->select('sectors.name AS sector_name')
->get();
dd( $result );如果您要求用户输入:
$result = DB::table('promotion_sector')
->join('promotions', 'id', '=', 'promotion_sector.promotion_id')
->join('sectors', 'id', '=', 'promotion_sector.sector_id')
->where( 'sectors.name', '=', $request->input('name_of_the_field') )
->select('sectors.name AS sector_name')
->get();
dd( $result );发布于 2015-05-28 05:47:25
使所有部门都能得到晋升。
试试这个:
class Promotion extends Model {
public function sectors() {
return $this->belongsToMany('App\Sector', 'promotion_sector', 'promotion_id', 'sector_id');
}
}若要验证,请在工匠修补程序中进行以下操作:
$pro = App\Promotion::find(1);
$pro->sectors;
$pro;您将获得与Id 1的促销相关的所有部门的列表。
做相反的事情,这是你在问题中提出的。
你需要这样做:
class Sector extends Model {
public function promotions() {
return $this->belongsToMany('App\Promotion', 'promotion_sector', 'sector_id', 'promotion_id');
}
}若要验证,请在工匠修补程序中进行以下操作:
$sec = App\Sector::find(1);
$sec->promotions;
$sec;您将得到与Id 1的部门相关的所有促销活动的列表。
https://stackoverflow.com/questions/30497540
复制相似问题