2017-07-27 69 views
1

這裏是我現在的問題IM試圖找出如何過濾其他表中記錄的查詢? - laravel

我有下面的例子

$users = User::where('country', $country) 

      ->where('age', '>=' , $lfmin) 
      ->where('age', '<=' , $lfmax) 
      ->get();     


      return $users; 

一個laravel查詢,這個作品出來都很好。但我現在有另一個名爲datingblockedusers的sql表。該表中的每條記錄都具有阻擋者和阻擋者的用戶標識。我也創造了datingblockeduser模型是這樣的

public static function checkblock($id1, $id2) 
{ 
    //check user is blocked 
    $query = Datingblockeduser::where('uone', $id1)->where('utwo', $id2)->get(); 
    if($query->count() > 0) 
    { 
     return true; 
    } 
    else 
    { 
     $query = Datingblockeduser::where('utwo', $id1)->where('uone', $id2)->get(); 
     if($query->count() > 0) 
     { 
      return true; 
     } 
     else 
     { 
      return false; 
     } 
    } 
} 

如何過濾我的主查詢,以便在查詢中的每個用戶的ID是不是在田野uone或utwo下datingblockeduser表中的靜態函數(用戶一個或兩個用戶)

編輯:我想實現一個塊列表類有關的朋友列表。我創建了一個新的遷移這樣

Schema::create('blocked_user', function(Blueprint $table) { 
     $table->increments('id'); 
     $table->integer('blocked_id')->unsigned()->index(); 
     $table->integer('user_id')->unsigned()->index(); 
     $table->foreign('blocked_id')->references('id')->on('users')->onDelete('cascade'); 
     $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); 
    }); 

,並在用戶模式,我這樣做

// blocked 
public function blocked() 
{ 
    $blocked = $this->belongsToMany('User', 'blocked_user', 'user_id', 'blocked_id'); 
    return $blocked; 
} 
public function block_user($blocked_id) 
{ 
    $this->blocked()->attach($blocked_id); // add friend 
    $blocked = User::find($blocked_id);  // find your friend, and... 
    $blocked->blocked()->attach($this->id); // add yourself, too 
} 
public function remove_blocked($blocked_id) 
{ 
    $this->blocked()->detach($blocked_id); // remove friend 
    $blocked = User::find($blocked_id);  // find your friend, and... 
    $blocked->blocked()->detach($this->id); // remove yourself, too 
} 

現在,現在我把它當作上面的查詢或現在的任何其他查詢的一部分上,使當然,我只返回不在阻止列表中的用戶?

+0

您需要創建這兩個表之間的關係改變主查詢; –

+0

一個多對多的關係?因爲據我可以看到它在兩個用戶ID之間有多對多的關係,但在同一個用戶表中。有沒有辦法使用約會鎖定表作爲同一個表中關係的數據透視表? – ram

+0

一對一我猜用戶可以被阻止或沒有? –

回答

0

你爲什麼不查詢所有阻止USER_ID比使用whereNotIn()

// get blocked user id by authenticated user. (change where condition yourself) 
$blockedId = Datingblockeduser::where('blocker_id', auth()->id())->pluck('id'); 

$users = User::where('country', $country) 
      ->whereNotIn('id', $blockedId) 
      ->where('age', '>=' , $lfmin) 
      ->where('age', '<=' , $lfmax) 
      ->get(); 
+0

謝謝先生!!!!!這正是我期待的!非常感謝! – ram

相關問題