许多人加入Laravel口才 [英] Many to Many join Laravel Eloquent

查看:80
本文介绍了许多人加入Laravel口才的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Laravel 4.1,我想加入Eloquent:所以我有3个表:

I'm using Laravel 4.1 and i want to make a join with Eloquent: So I have 3 table as:

表1(池):id,名称

Table 1 (pools): id, name

表2(贡献):id,金额,pool_id,contributor_id

Table 2 (contribution): id, amount, pool_id, contributer_id

表3(贡献者):id,姓氏

Table 3 (contributers): id, last_name

顺便说一下,我有3个模型:池,贡献者和贡献 预先感谢.

By the way i have 3 models : Pool, Contributer, and Contribution Thanks in advance.

推荐答案

您可以这样做:

$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();

有关更多详细信息,请参见 http://laravel.com/docs/eloquent#relationships .

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

这篇关于许多人加入Laravel口才的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆