使用两个不同的列laravel加入同一个表

时间:2017-10-17 03:53:59

标签: mysql laravel laravel-5 mysql-workbench

我在MySQl中尝试这些代码:

SELECT      
     A.*, 
     B.name,
     C.name
FROM 
     eventlog_tbl as A
     LEFT JOIN users B ON A.byuser=B.email 
     LEFT JOIN users C ON A.affectiveuser=C.email;

我在Laravel中尝试这些

return DB::table('eventlog_tbl')
            ->leftjoin('users', 'users.email', '=', 'eventlog_tbl.byuser')
            ->leftjoin('users', 'users.email', '=', 'eventlog_tbl.affectiveuser')
            ->select('eventlog_tbl.*','users.name','users.name')
            ->get();

如何将其转换为Laravel?

3 个答案:

答案 0 :(得分:4)

尝试以下代码:

$res =  DB::table('eventlog_tbl')
        ->leftjoin('users AS A', 'A.email', '=', 'eventlog_tbl.byuser')
        ->leftjoin('users AS B', 'B.email', '=', 'eventlog_tbl.affectiveuser')
        ->select('eventlog_tbl.*','A.name as byuser_name','B.name as affectiveuser_name')
        ->get();

    print_r($res);

答案 1 :(得分:1)

这是使用Laravel查询构建器编写的查询。

$events = DB::table('eventlog_tbl')
    ->select('eventlog_tbl.*', 'users_1.name', 'users_2.name')
    ->leftJoin('users AS users_1', 'users_1.email', '=', 'eventlog_tbl.byuser')
    ->leftJoin('users AS users_2', 'users_2.email', '=', 'eventlog_tbl.affectiveuser')
    ->get();

编辑:

$events = DB::table('eventlog_tbl')
    ->select('eventlog_tbl.*', 'users_1.name AS user_1', 'users_2.name AS user_2')
    ->leftJoin('users AS users_1', 'users_1.email', '=', 'eventlog_tbl.byuser')
    ->leftJoin('users AS users_2', 'users_2.email', '=', 'eventlog_tbl.affectiveuser')
    ->get();

问题是两个名称列都被称为相同的东西。根据公认的答案,这些也需要采用不同的别名。

答案 2 :(得分:0)

为什么不将此转换为使用关系?我可能有错误的关系,像这样:

class EventLog extends Model
{
    public function byUser()
    {
        return $this->hasOne(User::class, 'byuser', 'id');
    }

    public function affectiveUser()
    {
        return $this->hasOne(User::class, 'affectiveuser', 'id');
    }
}

然后

$event_log = EventLog::with(['byUser', 'affectiveUser')->all();


foreach ($event_log as $item) {
    echo $item->byUser->email();
}