I
I
inkkei2019-06-18 19:55:06
Yii
inkkei, 2019-06-18 19:55:06

How to correctly form a SQL query in Yii2?

I have three tables: book(id, title, author) and category(id, title) linked by table book_category(id, book_id, category_id). How can I make the correct andWhere so that books are displayed where category = $search_cat?

$books = Book::find()->orderBy('id DESC')
                    ->andWhere(['like', 'title', $search_title])
                    ->andWhere(['like', 'author', $search_author])
                    ->andWhere(['like', 'category', $search_cat]);

Relationships are configured as follows:
In the Book model:
public function getBookCategory()
    {
        return $this->hasMany(BookCategory::className(), ['book_id' => 'id']);
    }

    public function getCategories(){
        return $this -> hasMany(Category::className(), ['id' => 'category_id']) -> via('bookCategory');
    }

In the Category model:
public function getBookCategory()
    {
        return $this->hasMany(BookCategory::className(), ['category_id' => 'id']);
    }

In the BookCategory model:
public function getCategory()
    {
        return $this->hasOne(Category::className(), ['id' => 'category_id']);
    }

    public function getBook()
    {
        return $this->hasOne(Book::className(), ['id' => 'book_id']);
    }

Answer the question

In order to leave comments, you need to log in

5 answer(s)
D
D3lphi, 2017-08-08
@adem_145

Please recommend books for learning C++

Qt

D
devalone, 2017-08-08
@devalone

in general, you can create beautiful applications using C ++, or is there no way without C #?

No, just scary. Probably you will have to choose another language.

N
Nikolai Kargin, 2017-08-08
@kgnk

) And in general, you can create beautiful applications using C ++, or is there no way without C #?

Yes, you can, you can create the coolest applications on winApi ;)

S
Sergey Sakhno, 2017-08-09
@Punk_Joker

And I thought that beautiful applications can only be written in JavaScript, but they are written on what. Oh well, I still write ugly programs in this terrible C and ancient assembler

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question