2017-08-15 42 views
0

我需要使用方法(where)查詢模型並使用LIKE查找結果;Laravel multilpes與數組相似

它我的代碼:

public function scopeTags($query, $tags) 
{ 
    /* 
    * random = [ 'tag1', 'tag2', 'tag3', ...] 
    */ 
    $random = $tags[rand(0, count($tags) - 1)]; 
    return $query->where('tags', 'LIKE', "%{$random}%"); 
} 

我需要類似的東西:

public function scopeTags($query, $tags) 
{ 
    /* 
    * random = [ 'tag1', 'tag2', 'tag3', ...] 
    */ 
    foreach($tags as $tag) { 
     $random[] = "%{$tag}%"; 
    } 
    return $query->where('tags', 'LIKE', $random); 
} 

什麼是做到這一點的最好方法是什麼?

回答

1

您需要添加額外的where函數調用每個標籤:

public function scopeTags($query, $tags) 
{ 
    /* 
    * random = [ 'tag1', 'tag2', 'tag3', ...] 
    */ 
    foreach($tags as $tag) { 
     $query->where('tags', 'LIKE', "%{$tag}%"); //this will be a AND 
     //$query->OrWhere('tags', 'LIKE', "%{$tag}%"); //this will be a OR 
    } 
    return $query; 
} 

,或者如果你需要用括號模擬WHERE (tags like '%tag1%' AND tags like'%tag2%' AND ...) AND (something else)

public function scopeTags($query, $tags) 
{ 
    return $query->where(function($q) use($tags) { 
     foreach($tags as $tag) { 
      $q->where('tags', 'LIKE', "%{$tag}%"); //this will be a AND 
      //$q->OrWhere('tags', 'LIKE', "%{$tag}%"); //this will be a OR 
     } 
     return $q; 
    }); 
}