Answer the question
In order to leave comments, you need to log in
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();
}
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
Specific to the task
public static function getBooksByTag($tag)
{
$pattern = "(^{$tag}$)|(^{$tag},)|(,{$tag},)|(,{$tag}$)";
return Books::find()->where("tags REGEXP '{$pattern}'")->all();
}
do something incomprehensible
in_array returns true.
return Books::find()->where(['tags'=>implode(",", $tag)])->all();
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
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 questionAsk a Question
731 491 924 answers to any question