D
D
Dmitry Petrik2015-03-21 20:03:01
MySQL
Dmitry Petrik, 2015-03-21 20:03:01

Yii2. How to make a selection of records from the database by condition?

The task is this, you need to select from the database all the books that have a certain tag. In the database, each book has a tags field in which the tags are written as follows: "1,5,7,12". Those. just numbers separated by commas. In the model, I create the following function:

public static function getBooksByTag($tag)
    {
           return Books::find()->where(in_array($tag, explode(',', 'tags')))->all();
    }

By design, I call the function anywhere, and I get a list of the necessary books. In fact, this implementation does not work. The function always returns all books. How to finish this function to mind? What am I doing wrong here?
Of course, you can go head-on, go through all the books through foreach, go through all the tags for each book, comparing them with the one you are looking for. I just want to deal with that function above
Upd . Now did so. Everything works as it should. But can't it be more elegant?
public static function getBooksByTag($tag)
{
   $books = Books::find()->all(); //выгребаем все книжки
   $books_id[]=null; //это будет массив с id-шниками книг у которых есть нужные теги
    foreach ($books as $book){ 
        if (in_array($tag, explode(',', $book->tags))){  //проверяем есть ли наш тег в списке тегов книги
            $books_id[]=$book->id; //если тег есть, то добавляем id книги к нашему массиву  
         }
    }
return Books::findAll($books_id); //возвращаем все найденные книги
}

Answer the question

In order to leave comments, you need to log in

5 answer(s)
E
Egor Mokeev, 2015-03-21
@zetamen

Specific to the task

public static function getBooksByTag($tag)
{
    $pattern = "(^{$tag}$)|(^{$tag},)|(,{$tag},)|(,{$tag}$)";
    return Books::find()->where("tags REGEXP '{$pattern}'")->all();
}

And in a good way, the list of tags should be stored in a separate table and accessed through links

P
primitiveko, 2015-03-21
@primitiveko

var_dump(explode(',', 'tags')) check
$this->tags mb?

R
Rowdy Ro, 2015-03-21
@rowdyro

do something incomprehensible
in_array returns true.

return Books::find()->where(['tags'=>implode(",", $tag)])->all();

M
Mikhail Osher, 2015-03-22
@miraage

Let's start with the fact that books / tags were not implemented in the best way.
You sew them into a book, although it should have been done through many-to-many.
books: id, title, ...
tags: id, title, ...
books_tags: book_id, tag_id

A
Alexander Isaev, 2015-04-16
@almix

Mikhail Osher, why didn't the person implement it in the best way? Why many-to-many? The extra table appears in the database.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question