0

Working with Yii framework 2.0 I tried to retrieve data from my relational database tables following the documentation here http://www.yiiframework.com/doc-2.0/guide-db-active-record.html

Below is the code sample under the section Lazy and Eager Loading.

$customers = Customer::find()->limit(100)->with([
    'orders' => function($query) {
        $query->andWhere('subtotal>100');
    },
])->all();

In my case I want to pass a parameter to the andWhere() method as following.

$param = 'something flexible';
$customers = Customer::find()->limit(100)->with([
    'orders' => function($query) {
        $query->andWhere('subtotal > ' . $param);
    },
])->all();

It does not work this way. What do I miss or how can I pass the parameter from the first line to the andWhere() method?

1 Answer 1

1

I found the solution as following.

$param = 'something flexible';
$customers = Customer::find()->limit(100)->with([
    'orders' => function($query) use($param) {
       $query->andWhere('subtotal > ' . $param);
    },
])->all();
Sign up to request clarification or add additional context in comments.

1 Comment

Please do not construct queries like this. andWhere() allows you to have $param bound and escaped for you like this: ->andWhere('subtotal > :param', [':param' => $param]). See also: yiiframework.com/doc-2.0/guide-db-query-builder.html#where

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.