Serge
Serge

Reputation: 72

Yii - find records with zero related records

There are two models: Auteurs and Books. Auteurs model contains following relations:

public function relations() {
    return array(
        'books' => array(self::MANY_MANY, 'Books','a_liens(id_auteur,id_book)'),
        'booksCount' => array(self::STAT, 'Books', 'a_liens(id_auteur,id_book)'),
    );
}

How to write criteria to get all Auteurs with zero booksCount?

Upvotes: 0

Views: 26

Answers (1)

rob006
rob006

Reputation: 22174

Instead of counting books, you may just find Auteurs models without any book - result is the same, but question is different. You may achieve this by using LEFT JOIN and finding records with missing books:

$auteurs->with([
    'books' => [
        'together' => true,
        'select' => false,
        'joinType' => 'LEFT JOIN',
        'condition' => 'books.id IS NULL',
    ],
]);

Upvotes: 1

Related Questions