Томица Кораћ
Томица Кораћ

Reputation: 2662

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?

Upvotes: 5

Views: 6789

Answers (1)

Umut Sirin
Umut Sirin

Reputation: 2502

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

}

Upvotes: 13

Related Questions