TheDevWay
TheDevWay

Reputation: 1413

Issue in building search with like query using QueryBuilder yii2

I am trying to make a search query for my website blogs using yii2 QueryBuilder , but there is an error like this when i try to execute my query with ->all() . here is the error : strtr() expects parameter 1 to be string, object given . And here is my model and controller . I have no idea what is causing the problem .

controller :

public function actionSearchBlog()
    {
        $model = new Blog();

        if ($model->load(Yii::$app->request->post())) {
            Blog::searchBlog($model->search);
        } else {
            return $this->render('search',['model' => $model]);
        }
    }

Model :

public static function searchBlog($search = null)
    {
        $search = new Query();
        $result = $search->select('id','title','blog','picture')
          ->from('blog')
          ->where(['like' , 'title' , $search])
          ->orWhere(['like' , 'blog' , $search])
          ->all();
        echo '<pre>';
        var_dump($result);
        die();
    }

I tried the query without ->all() at the end , but the var_dump value will be the the query itself and it won't be executed . and with ->all() I get that error.

Upvotes: 0

Views: 1070

Answers (3)

suibber
suibber

Reputation: 267

Are you sure the $search is string or array?

like: operand 1 should be a column or DB expression, and operand 2 be a string or an array representing the values that the column or DB expression should be like. For example, ['like', 'name', 'tester'] will generate name LIKE '%tester%'.

When the value range is given as an array, multiple LIKE predicates will be generated and concatenated using AND. For example, ['like', 'name', ['test', 'sample']] will generate name LIKE '%test%' AND name LIKE '%sample%'. The method will properly quote the column name and escape special characters in the values.

Sometimes, you may want to add the percentage characters to the matching value by yourself, you may supply a third operand false to do so. For example, ['like', 'name', '%tester', false] will generate name LIKE '%tester'.

Upvotes: -1

ineersa
ineersa

Reputation: 3445

public static function searchBlog($search = null)
{
    $query = new Query();
    $result = $query->select('id','title','blog','picture')
      ->from('blog')
      ->where(['like' , 'title' , $search])
      ->orWhere(['like' , 'blog' , $search])
      ->all();
    echo '<pre>';
    var_dump($result);
    die();
}

This will work. But start using IDE, and watch on variables you are using.

Upvotes: 4

Double H
Double H

Reputation: 4160

Try your ActiveQuery as:--

$result = (new Query())->select('id','title','blog','picture')
        ->from('blog')
        ->where(['like' , 'title' , $search])
        ->orWhere(['like' , 'blog' , $search])
        ->all();

    echo '<pre>';
    var_dump($result);
    die();

Upvotes: 0

Related Questions