2015-09-27 56 views
0

我需要根據一些條件篩選項目集合。聽到是這種情況。Laravel 5.1雄辯:如何根據某些條件檢索集合?

//This is part of projects table schema 
    Schema::create('projects', function (Blueprint $table) { 
      ... 
      $table->smallInteger('source_lang_id')->index()->unsigned(); 
      $table->smallInteger('target_lang_id')->index()->unsigned(); 
      ... 
     }); 
//This is part of translator_infos schema 
Schema::create('translator_infos', function (Blueprint $table) { 
      .... 
      $table->smallInteger('from_l_1_id')->index()->unsigned(); 
      $table->smallInteger('from_l_2_id')->index()->nullable()->unsigned(); 
      $table->smallInteger('from_l_3_id')->index()->nullable()->unsigned(); 
      $table->smallInteger('from_l_4_id')->index()->nullable()->unsigned(); 
      $table->smallInteger('to_l_1_id')->index()->unsigned(); 
      $table->smallInteger('to_l_2_id')->index()->nullable()->unsigned(); 
      $table->smallInteger('to_l_3_id')->index()->nullable()->unsigned(); 
      $table->smallInteger('to_l_4_id')->index()->nullable()->unsigned(); 
     .... 
     }); 

因此,每個項目都有源語言和目標語言。譯員可能有4個語言對。我需要的是過濾項目集合並查找其源語言和目標語言至少與其中一個翻譯語言對匹配的項目,並將此集合傳遞給視圖。現在我正在使用的查詢如下:

$projects=Project::orderBy('created_at', 'desc')->where('status_id', "=", 1)->paginate(15); 

如何將此條件添加到查詢中? 我試着用以下的範圍在我的項目模型,但它是適合於一個只對語言:

public function scopeLangMatch($query, $from, $to) 
    { 
     $match=[ 
      'source_lang_id'=>$from, 
      'target_lang_id'=>$to 
     ]; 
     return $query->where($match); 
    } 
+1

您將需要多個建議設置範圍(http://laravel.com/docs/5.1/eloquent#query-scopes),以便您可以傳遞調用'Project :: langMatch($源,$ to) - > orderBy(...)...'。 – Hailwood

+0

@Hailwood使用這種方法,我只能過濾一對語言。我已經將這個範圍添加到了我的問題中。還有其他解決方案嗎? –

回答

1

嘗試重寫你的範圍如下:

public function scopeLangMatch($query, $matches) { 

    $useOr = false; 
    foreach($matches as $from => $to){ 
     $match=['source_lang_id'=>$from, 'target_lang_id'=>$to]; 
     $query = ($useOr ? $query->orWhere($match) : $query->where($match)); 
     $useOr = true; 
    } 

    return $query; 
} 

然後你可以使用它作爲

Project::langMatch([ 
    1 => 2, 
    3 => 4, 
    5 => 6, 
    7 => 8 
])->get(); 

這也使您能夠靈活我在項目模型中定義的範圍如下在將來定義更多或更少的匹配,而不必修改代碼或擔心參數匹配。

0

感謝@Hailwood建議,我找到了解決辦法。

public function scopeLangMatch($query, $from1,$from2,$from3,$from4, $to1, $to2, $to3, $to4) 
    { 
     $match=[ 
      'source_lang_id'=>$from1, 
      'target_lang_id'=>$to1 
     ]; 
     $match2=[ 
      'source_lang_id'=>$from2, 
      'target_lang_id'=>$to2 
     ]; 
     $match3=[ 
      'source_lang_id'=>$from3, 
      'target_lang_id'=>$to3 
     ]; 
     $match4=[ 
      'source_lang_id'=>$from4, 
      'target_lang_id'=>$to4 
     ]; 
     return $query->where($match)->orWhere($match2)->orWhere($match3)->orWhere($match4); 
    } 
+1

我可能會建議你改變範圍來取一組source =>來配對。我將在下面發佈這個想法。 – Hailwood

+0

@Hailwood謝謝你的幫助。我在等你的答案。 –