yii2 中間關聯表 via() viaTable()

大飛_dafei發表於2018-12-18
viaTable()
    /**
     * @link https://www.yiiframework.com/doc/guide/2.0/zh-cn/db-active-record#junction-table
     * user 表 id
     * book_user 表 user_id  book_id
     * book 表 id
     *
     * #SELECT * FROM `book` WHERE `id`='1'
     * $book = Book::findOne(1)
     *
     * #SELECT * FROM `book_user` WHERE `book_id`=1
     * #SELECT * FROM `user` WHERE `id` IN ('1', '2',....)
     * $model->bookUserItems;
     *
     * @return \yii\db\ActiveQuery
     */
    public function getBookUserItems()
    {
        return $this->hasMany(User::className(), ['id' => 'user_id'])
            ->viaTable('book_user',['book_id'=>'id']);
    }

官方地址: 中間關聯表(Relations via a Junction Table)

相關文章