mae
mae

Reputation: 15666

Yii2: Filter query by pivot table when using `joinWith()`

Take the following sample Cart model. It has a CartItem "pivot record/table" which links it to Item.

class Cart extends ActiveRecord {

    public function getCartItems() {
        return $this
            ->hasMany(CartItem::class, ['cart_id' => 'id'])
            ->inverseOf('cart');
    }

    public function getItems($callback = null) {
        return $this
            ->hasMany(Item::class, ['item_id' => 'id'])
            ->via('cartItems', $callback);
    }

}

(Example #1) At this point I would be able to filter either by Item's activequery or CartItem's query like so:

$booksAddedToCartSinceYesterday = $cart
    ->getItems(function($cartItemQuery) {
        $cartItemQuery->andWhere('cartItem.created_at > NOW()');
    })
    ->andWhere(['item.category' => 'books']);

(Example #2) But how do I accomplish the same when I use the static find() method in combination with joinWith()? In the following example I am only able to filet by Item's ActiveQuery, but I no longer have any reference to the CartItem's ActiveQuery object:

$booksAddedToCartSinceYesterday = Cart::find()
    ->andWhere(['cart.user_id' => $some_user_id])
    ->joinWith([
        'items' => function($itemQuery) {
            $itemQuery->andWhere(['item.category' => 'books']);
        },
    ]);

How do I modify the code above so that I am able to filter CartItem junction table records like I did in my example #1? How do I access the junction ActiveQuery object so that I can call $cartItemQuery->andWhere('cartItem.created_at > NOW()');?

Upvotes: 0

Views: 388

Answers (1)

Shringiraj Dewangan
Shringiraj Dewangan

Reputation: 784

you can pass any variable value in anonymous function with use keyword link below

make your magic code here for filter or any

->joinWith([
    'items' => function($itemQuery) use ($var1,$var2){
        $itemQuery->andWhere(['item.category' => 'books']);
        $itemQuery->andWhere(['some_condition' => $var1]); <<<---------
    },
]);

Upvotes: 0

Related Questions