Laravel 5 - 使用数据库表执行连接

时间:2016-02-22 17:46:26

标签: laravel laravel-5 laravel-5.1

我有几个这样的模式

Schema::create('users', function (Blueprint $table) {
    $table->increments('id');
    $table->string('userName')->default('');
    $table->string('userEmail')->default('');
    $table->tinyInteger('active')->default(1);
    $table->integer('departmentId')->unsigned()->default(0);
    $table->foreign('departmentId')->references('departmentId')->on('departments')->onDelete('cascade');
    $table->timestamps();
});

Schema::create('departments', function (Blueprint $table) {
    $table->primary('departmentId');
    $table->integer('departmentId')->unsigned()->default(0);
    $table->string('departmentName')->default('');
    $table->tinyInteger('active')->default(1);
    $table->timestamps();
});

因此,用户属于某个部门,而部门可以拥有许多用户。

在我的一个控制器中,我使用以下内容来获取特定部门的用户列表

$users = User::select('userName', 'id')->where('departmentId', 2)->get();

因为我从Active Directory获取部门,所以我发现这不是一个好方法,因为部门的ID会发生变化。因此,我现在需要通过departmentName获取用户。目前我正在尝试这样的事情

$test = DB::table('users')
        ->join('departments', 'users.departmentId', '=', 'departmentId')
        ->select('users.userName', 'users.id')
        ->get();

但是,这会返回以下错误

SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'departmentId' in on clause is ambiguous (SQL: select `users`.`userName`, `users`.`id` from `users` inner join `departments` on `users`.`departmentId` = `departmentId`)

如何让所有用户获得特定部门名称?所以说我想让所有属于技术部门的用户,我怎么能这样做呢?

由于

1 个答案:

答案 0 :(得分:2)

您错过了departments表名,因此sql将departmentId呈现为不明确的,因为它可以在users和departments表中找到。您的查询应该是这样的。

$test = DB::table('users')
    ->join('departments', 'users.departmentId', '=', 'departments.departmentId')
    ->select('users.userName', 'users.id')
    ->get();

但是如果你想按部门名称进行过滤,那么你应该像这样添加一个where子句

 $test = DB::table('users')
    ->join('departments', 'users.departmentId', '=', 'departments.departmentId')
    ->select('users.userName', 'users.id')
    ->where('departments.departmentName', "department name goes here")
    ->get();