Reputation: 89
I have the Following models relationship.
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');
}
}
I want to get the promotions which are in given sectors.
For example,
All the promotions in sector A and B
Upvotes: 0
Views: 464
Reputation: 79
To get all sectors associated with a promotion.
Try this:
class Promotion extends Model {
public function sectors() {
return $this->belongsToMany('App\Sector', 'promotion_sector', 'promotion_id', 'sector_id');
}
}
To verify, try this in artisan tinker:
$pro = App\Promotion::find(1);
$pro->sectors;
$pro;
You will get the list of all sectors associated with Promotion with Id 1.
To do the opposite, that you have asked in the question.
You need to do this:
class Sector extends Model {
public function promotions() {
return $this->belongsToMany('App\Promotion', 'promotion_sector', 'sector_id', 'promotion_id');
}
}
To verify, try this in artisan tinker:
$sec = App\Sector::find(1);
$sec->promotions;
$sec;
You will get the list of all the promotions associated with sector with Id 1.
Upvotes: 1
Reputation: 4020
I don't know which type of relationship you are using. I presume it to be Many-To-Many
Relationship.
So here's the code you can try:
$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 );
And if you are asking for the input from the user:
$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 );
Upvotes: 0