Many to Many join Laravel Eloquent

laravel-4

Solution

You can do it this way:

$result = Pool::join('Contribution', 'Pool.id', '=', 'Contribution.pool_id')
->join('Contributer', 'Contribution.contributer_id', '=', 'Contributer.id')->get();

Or, if you define the relationships in models, such as:

class Pool extends Eloquent {
...
public function contributers(){
        return $this->belongsToMany('Contributer', 'contribution');
    }
...
}

class Contributer extends Eloquent {
...
public function pools(){
        return $this->belongsToMany('Pool', 'contribution');
    }
...
}

you can access related models as:

$contributers = $pool->contributers()->get(); // Returns Illuminate/Database/Eloquent/Collection object containing contributers of the pool

or you can do eager loading such as:

$result = Pool::with('contributers')->get();

see http://laravel.com/docs/eloquent#relationships for more details.

Problem

I'm using Laravel 4.1 and i want to make a join with Eloquent: So I have 3 table as: Table 1 (pools): id, name Table 2 (contribution): id, amount, pool_id, contributer_id Table 3 (contributers): id, last_name By the way i have 3 models : Pool, Contributer, and Contribution Thanks in advance.

Original source