F
F
Fear12018-10-02 20:04:45
Yii
Fear1, 2018-10-02 20:04:45

How can I find posts that have all the tags I need?

I can’t figure out how to get all the posts from the table that have all the tags I need.
I use the following construction:

$query = Card::find()->joinWith('tags')->where(['tags.id' => 2])->joinWith('tags t')->where(['t.id' => 1]);

I get all the cards that have and . But also cards in which there is simply , but without . I need to find all cards that have both , and , but not just one. Where did I take a wrong turn? Upd. Models: Tags.phptags.id = 1tags.id =2tags.id = 1tags.id = 2
tags.id = 1tags.id =2
public function getCard()
    {
        return $this->hasMany(Card::className(), ['id' => 'card_id'])
                    ->viaTable('card_tags', ['tags_id' => 'id']);
    }

card.php
public function getTags()
    {
        return $this->hasMany(Tags::className(), ['id' => 'tags_id'])
                    ->viaTable('card_tags', ['card_id' => 'id']);
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Kulay, 2018-10-02
@Fear1

Probably, the intermediate table is enough to filter by the id of the tag, since it is present in it

Card::find()
  ->leftJoin('card_tags t1', 't1.card_id = card.id')
  ->leftJoin('card_tags t2', 't2.card_id = card.id')
  ->where([
    'and',
    ['t1.tags_id' => 1],
    ['t2.tags_id' => 2]
  ]);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question