A
A
Alexander Nevsky2018-12-12 13:34:12
Yii
Alexander Nevsky, 2018-12-12 13:34:12

How to make a selection of similar products in Yii2?

There are 3 linked tables using 2 linking tables.
The books table is associated with the genres table, just like books is associated with tags
5c10e3ba1d294326479527.png5c10e3c1950f3730471934.png
The relationship is normal

public function getLinkGenresBooks()
    {
        return $this->hasMany(LinkGenresBooks::className(), ['books_id' => 'id']);
    }
    public function getGenres()
    {
        return $this->hasMany(Genres::className(), ['id' => 'genres_id'])->via('linkGenresBooks');
    }

    public function getLinkTagsBooks()
    {
        return $this->hasMany(LinkTagsBooks::className(), ['books_id' => 'id']);
    }
    public function getTags()
    {
        return $this->hasMany(Tags::className(), ['id' => 'tags_id'])->via('linkTagsBooks');
    }

I need to display similar books on the book page. I think the correct logic would be to choose books that have at least 2 genres AND 2 tags the same as the book on the page I'm on.
There is a problem in composing this SQL query. I tried to experiment, it seems that something comes out, but there is no such thing as 2 genres and 2 tags.
$test = Books::find()->joinWith('genres g')->joinWith('tags t')->where(['or', ['g.id' => [1, 21, 30]]])->andWhere(['or', ['t.id' => [1, 5]]])->all();

Maybe I'm not quite right with the logic, then tell me how it would be more correct to do it.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Timofeev, 2018-12-12
@webinar

Since your connection is HasMany, the number will fail. It is necessary either to use GROUP BY or to receive in several requests, choosing id-shniki.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question