I'm trying to build a Laravel app using a customized database structure. I have tables types
, units
, content
, and a pivot table called relations
. The structure of the relations
table is such:
---------------------------------------------
| id | relation_type | first_id | second_id |
---------------------------------------------
| 1 | type_unit | 1 | 2 |
---------------------------------------------
| 2 | unit_content | 2 | 3 |
---------------------------------------------
In other words, the first three tables have many-to-many relations among themselves, and the fourth one is the pivot table for all the relations. How can I use the Eloquent's BelongsToMany
method with this pivot table structure, i.e. how can I select only the pivot table's records relevant to the given relation? For example, how would I use only the type_unit relations in this:
class Type extends Eloquent {
public function units()
{
return $this->belongsToMany('Unit', 'relations');
}
}
but at the same time ignore the unit_content relations?
To create a pivot table we can create a simple migration with artisan make:migration or use Jeffrey Way's package Laravel 5 Generators Extended where we have a command artisan make:migration:pivot.
whereHas() works basically the same as has() but allows you to specify additional filters for the related model to check.
You have to run - php artisan make:migration create_project_user_table --create --table=project_user to create the pivot table migration file after that you can copy/paste code in this migration file and run migrate command to create pivot table in your database.
belongsToMany
would accept 3rd and 4th arguments. You can see it in documentation: http://laravel.com/docs/eloquent#relationships
But the thing that is not in documentation is that you can constraint your relation by chaining the query builder functions like where
, orderBy
etc.
So your code would be something like:
class Type extends Eloquent {
public function units()
{
return $this->belongsToMany('Unit', 'relations', 'first_id', 'second_id')
->withPivot(['relation_type'])
->where('relations.relation_type', '=', 'type_unit');
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With