Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Many to Many join Laravel Eloquent

Tags:

laravel-4

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.

like image 545
Nabil Lemsieh Avatar asked Apr 18 '14 16:04

Nabil Lemsieh


1 Answers

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.

like image 148
eaykin Avatar answered Sep 30 '22 18:09

eaykin