Many to Many join Laravel Eloquent

回眸只為那壹抹淺笑 提交于 2019-12-06 04:46:59

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.

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