2016-03-14 49 views
0

我使用Laravel 5和我有3個數據庫表projectsapplicationsusers及其表結構是如下:Laravel多個表數據濾波器

項目

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中返回NULL

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 
    }] 
} 

有沒有人有一個解決的辦法?

回答

0

我只是想出如何利用兩個不同的查詢要做到這一點,並結合在一起。

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" 
}] 
0
DB::table('projects') 
    ->leftjoin('applications', function($join){ 
     $join->on('applications.project_id', '=', 'projects.id') 
      ->where('applications.user_id', '=', $user->id); 
    }) 
    ->whereNull('applications.id') 
    ->get(); 

認爲這就是你要找的

+0

這個查詢仍然給我與'project.id' ='NULL'相同的結果:( – Woody

+0

你怎麼試圖檢索那個值 – Chris

+0

對不起,你是什麼意思?我不太明白你的問題 – Woody