我使用的是Laravel 5,我有3个数据库表projects、applications、users,它们的表结构如下:
项目
Schema::create('projects', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->text('description');
$table->char('status',1);
$table->timestamps();
});应用程序
Schema::create('applications', function (Blueprint $table) {
$table->increments('id');
$table->integer('project_id')->unsigned()->index();
$table->integer('user_id')->unsigned()->index();
$table->char('status');
$table->timestamps();
});用户
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->integer('role');
$table->string('name');
$table->string('email')->unique();
$table->string('password', 60);
$table->rememberToken();
$table->timestamps();
});现在,我想执行一个查询,以返回特定用户尚未向该项目提交任何应用程序的所有项目。到目前为止,这是我能得到的最接近的结果,但是对于每个没有应用程序的项目,它将在projects.id中返回projects.id。
DB::table('projects')
->leftjoin('applications', 'applications.project_id', '=', 'projects.id')
->where('applications.user_id', '!=', $user->id)
->orWhereNull('applications.id')
->get();查询结果
{
"total":1,
"per_page":5,
"current_page":1,
"last_page":1,
"next_page_url":null,
"prev_page_url":null,
"from":1,"to":1,
"data":[{
"id":null,
"name":"Project2",
"description":"Project2 detail",
"status":null,
"created_at":null,
"updated_at":null,
"project_id":null,
"user_id":null
}]
}有人有办法解决这个问题吗?
发布于 2016-03-15 03:12:26
我只知道如何使用两个不同的查询并将它们组合在一起来完成这一任务。
1)选择所有用户应用程序的project_id
$user_applications = Application::where('user_id', '=', $user->id)
->select('project_id as id')
->get();2)选择项目不在以前的列表中的项目
$projects_not_applied = DB::table('projects')
->whereNotIn('id',$user_applications)
->get();查询结果(用户未申请项目2):
[{
"id":"2",
"name":"Project2",
"description":"Project2 detail",
"status":"n",
"created_at":"2016-03-14 15:09:58",
"updated_at":"2016-03-14 15:09:58"
}]发布于 2016-03-14 08:06:15
DB::table('projects')
->leftjoin('applications', function($join){
$join->on('applications.project_id', '=', 'projects.id')
->where('applications.user_id', '=', $user->id);
})
->whereNull('applications.id')
->get();你觉得这就是你想要的
https://stackoverflow.com/questions/35982207
复制相似问题