Laravel从两列连接两个表

时间:2014-11-12 05:40:15

标签: laravel eloquent

如何使用Laravel Eloquent实现this之类的功能? 我没有找到如何使用Eloquent两次命名同一个表。

感谢。

表用户

id | first_name | last_name |
---+------------+-----------+
 1 | John       | Doe       |
 2 | Jane       | Doe       |
 3 | Some       | Name      |

表格印章

id |    date    | applicant_id  | app_by_id |
---+------------+---------------+-----------+
 1 | 2013-03-15 | 1             | 2         |
 2 | 2013-03-10 | 2             | 3         |
 3 | 2013-03-13 | 2             | 1         |

我想要展示的内容:

    date    | applicant | app_by    |
------------+-----------+-----------+
 2013-03-15 | John Doe  | Jane Doe  |
 2013-03-10 | Jane Doe  | Some Name |
 2013-03-13 | Jane Doe  | John Doe  |

所需的等效SQL查询:

SELECT s.date,
CONCAT_WS(' ', NULLIF(u1.first_name, ' '), NULLIF(u1.last_name, ' ')) AS applicant,
CONCAT_WS(' ', NULLIF(u2.first_name, ' '), NULLIF(u2.last_name, ' ')) AS app_by
FROM stamp s
LEFT JOIN users u1 ON s.applicant_id = u1.id
LEFT JOIN users u2 ON s.app_by_id = u2.id

2 个答案:

答案 0 :(得分:1)

如果您已经拥有它,为什么不使用这样的原始SQL语句?

$data = DB::Select("SELECT s.date,
    CONCAT_WS(' ', NULLIF(u1.first_name, ' '), NULLIF(u1.last_name, ' ')) AS applicant,
    CONCAT_WS(' ', NULLIF(u2.first_name, ' '), NULLIF(u2.last_name, ' ')) AS app_by
    FROM stamp s
    LEFT JOIN users u1 ON s.applicant_id = u1.id
    LEFT JOIN users u2 ON s.app_by_id = u2.id;"
);

Eloquent旨在让您的生活更轻松。如果你试图强迫一个广泛的SQL语句进入Eloquent它不会让你的生活更轻松。

答案 1 :(得分:1)

您可以像这样加入表格 -

$stamp = Stamp::join('users as application', 'application.id', '=', 'stamps.applicant_id')
    ->join('users as app_by', 'app_by.id', '=', 'stamps.app_by_id')
    ->select(
            'data',
            DB::raw("CONCAT(application.first_name,' ', application.last_name) as application"),
            DB::raw("CONCAT(app_by.first_name,' ', app_by.last_name) as app_by")
    )
    ->get();

现在,如果你想通过在模型上定义关系来做到这一点,那么 -

class Stamp extends Eloquent {

    public function application()
    {
        return $this->belongsTo('User', 'applicant_id');
    }

    public function appBy(){
        return $this->belongsTo('User', 'app_by_id');
    }

}

查询

$stamp = Stamp::with('application', 'appBy')->get();
foreach($stamp as $s){
        echo $s->data . '    ';
        echo $s->application->first_name. ' ', $s->application->last_name. '    ';
        echo $s->appBy->first_name. ' ', $s->appBy->last_name;
        echo '<br>';
}