Yii2 左连接查询不为空条件

Yii2 left join query with not null condition

我有书和借书table,想查询所有借书不为空的借书

table结构是

tbl_books
   id
   name

然后借书

tbl_borrowed_books
    id
    book_id
    borrowed_at

所以在我的查询中我有

$query = TblBooks::find()->leftJoin('tbl_borrowed_books','tbl_borrowed_books.book_id = tbl_books.id')->all();

所以现在我想添加一个条件,我想获得所有在 tbl_borrowed_books

中有记录的书

如何检查是否为空

有点像

   $query = TblBooks::find()->leftJoin('tbl_borrowed_books','tbl_borrowed_books.book_id = tbl_books.id')
  ->where('<>','') //stuck here on adding the not null condition
  ->all();

如果您坚持使用 LEFT JOIN,那么您可以检查第二个 table 中不能将 NULL 作为有效值的任何列。例如,您可以使用它的主键或外键列。

 $query = TblBooks::find()
    ->leftJoin(
        'tbl_borrowed_books',
        'tbl_borrowed_books.book_id = tbl_books.id'
    )->where(['not', 'tbl_borrowed_books.book_id', NULL])
    ->all();

但最好使用INNER JOIN,因为它只记录returns 两个table 中都存在匹配记录的记录。所以它做的事情和 WHERE tbl_borrowed_books.book_id IS NOT NULL 做的完全一样。

$query = TblBooks::find()
    ->innerJoin(
        'tbl_borrowed_books',
        'tbl_borrowed_books.book_id = tbl_books.id'
    )->all();

更多基于ActiveRecord的解决方案来获取交叉借书:

$borrowedBooks = TblBooks::find()->joinWith('borrowedBooks', true, 'inner join')->all();