Greedy Parametrized Relation

Hi guys.

Can you please provide an example of greedy parametrized relation?

Here’s an example from docs:


class Customer extends \yii\db\ActiveRecord

{

    public function getBigOrders($threshold = 100)

    {

        return $this->hasMany(Order::className(), ['customer_id' => 'id'])

            ->where('subtotal > :threshold', [':threshold' => $threshold])

            ->orderBy('id');

    }

}

Suppose I want to get the list of all customers and their orders, something like this:

$customers = Customer::find()->getBigOrders(200)->all()

But the code above throws an error.

What is the error?

Here’s the model (Client.php):


public function getRegion($param = null)

{

    // in order to simplify example, $param is not actually used

    // and hasOne instead of hasMany

    return $this->hasOne(Region::className(), ['id' => 'region_id']);

}



Here’s test usage (ClientController.php)


public function actionTest()

{

    $items = Client::find()->getRegion(1)->all();

    return 'ok';

}

The error is




Strict – yii\base\ErrorException


call_user_func_array() expects parameter 1 to be a valid callback, non-static method app\models\Client::getRegion() should not be called statically


 in /media/psf/Home/web/phone.local/vendor/yiisoft/yii2/yii/db/ActiveQueryTrait.php at line 46


    public function __call($name, $params)

    {

        if (method_exists($this->modelClass, $name)) {

            array_unshift($params, $this);

            call_user_func_array([$this->modelClass, $name], $params);

            return $this;

        } else {

            return parent::__call($name, $params);

        }

    }



Php 5.5

I created an issue #1580 for this. The current workaround is to use a scope which can be called statically:

You can create a scope like this currently and this should work:




public static function getBigOrders($query, $threshold = 100)

{

   $query->andWhere('id in (SELECT customer_id FROM orders WHERE subtotal > :threshold)', [':threshold' => $threshold]);

}   



It works now with my PHP 5.4 install without any problems (had this problem in another instance which I rectified by bringing instances in sync on same versions). O’rey you may want to check your PHP version and ini settings, as well as if you probably have the latest version of the yii repo code (using composer update).

5.5 now, will try to downgrade.

Yii is latest, of course. I always do update in case of strange bugs.