Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eloquent ORM / Laravel - use custom pivot table structure

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?

like image 943
Томица Кораћ Avatar asked Jul 20 '13 21:07

Томица Кораћ


People also ask

How do I create a pivot table model in Laravel?

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.

What is the use of whereHas in Laravel?

whereHas() works basically the same as has() but allows you to specify additional filters for the related model to check.

How do I create a pivot table in Laravel 8?

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.


1 Answers

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');
    }

}
like image 104
Umut Sirin Avatar answered Jan 01 '23 10:01

Umut Sirin