Many to Many join Laravel Eloquent

独自空忆成欢 提交于 2019-12-10 10:48:16

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/23157825/many-to-many-join-laravel-eloquent

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!