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?

Jonnny
  • 4,939
  • 11
  • 63
  • 93
O Connor
  • 4,236
  • 15
  • 50
  • 91

1 Answers1

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();
O Connor
  • 4,236
  • 15
  • 50
  • 91
  • 1
    Please do not construct queries like this. [andWhere()](http://www.yiiframework.com/doc-2.0/yii-db-query.html#andWhere%28%29-detail) allows you to have `$param` bound and escaped for you like this: `->andWhere('subtotal > :param', [':param' => $param])`. See also: http://www.yiiframework.com/doc-2.0/guide-db-query-builder.html#where – DaSourcerer Mar 02 '15 at 10:47