We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Loop where like % in query ()

I wan to loop where like % in query ()

Please help me !

Article::query()

        ->where("ar_type_id = '$type_id'")

        ->andWhere("ar_active = 'Y'")

        foreach($arr_tag as $tag) {
             ->andWhere("ar_name LIKE '%$tag' ")
        }

        ->orderBy("ar_view_count DESC")

        ->limit(9)

        ->execute();


145.0k
Accepted
answer
edited Mar '16

You sure you want AND not Or ? Its pretty easy :

$query = Article::query()
    >where("ar_type_id = '$type_id'")
    ->andWhere("ar_active = 'Y'")
    ->orderBy("ar_view_count DESC")
    ->limit(9);
     foreach($arr_tag as $tag) {
             $query->andWhere("ar_name LIKE '%$tag' ");
    };
    $result = $query->execute();

Also you should use bound parameters.

You sure you want AND not Or ? Its pretty easy : It ok. thanks

$query = Article::query()
   >where("ar_type_id = '$type_id'")
  ->andWhere("ar_active = 'Y'")
  ->orderBy("ar_view_count DESC")
  ->limit(9);
   foreach($arr_tag as $tag) {
            $query->andWhere("ar_name LIKE '%$tag' ");
  };
  $result = $query->execute();

Also you should use bound parameters.



7.0k

You can set the search as function; Below is some code just like above.

 public function search($search)
    {
        $bits = explode(' ',trim($search));
        $query = $this->query()->orderBy('id')->where('title like :search:',['search'=>'%'.array_shift($bits).'%']);

        foreach($bits as $key => $bit){
            $query->andWhere("title like :search{$key}:",["search{$key}"=>'%'.$bit.'%']);
        }
        return $query->execute();
    }