active-record icon indicating copy to clipboard operation
active-record copied to clipboard

FR ActiveRecod relation parameters in with() call as array

Open wapmorgan opened this issue 7 years ago • 3 comments

Feature Request. Hello. I'm using AR and created a relation for current user's relational record in another table (user's vote result of poll). Relation looks this way:

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getUserPollStatus($id)
    {
        return $this->hasOne(UserPollStatusItem::className(),
            ['poll_id' => 'id'])
            ->where(['user_id' => $id])
            ->limit(1);
    }

I was expecting that could be able to enable eager loading for this query and that this will look like:

if ($user_id !== null)
  $query->with(['userPollStatus' => [$user_id]]);

But it looks that this doesn't work, it supports only callbacks. Also, it does not check really passed value.

What about adding ability to pass an array instead of callback to modify relation query?

wapmorgan avatar Jul 11 '17 12:07 wapmorgan

A callback is the most flexible way of modifying a query, what would be the advantage of passing an array? Also, is the class you have created the relation in a User or something else?

cebe avatar Jul 11 '17 23:07 cebe

@cebe the advantage is an eager loading of parametrized relational data without anonymous callback. The scheme is following:

Table: users                     Table: users_poll_statuses
----------------                 -----------------------------------
id              -------------->  user_id
...                              id
...                              ...

I propose to implement a shortcut. It's just shortier to write 'relationName' => [$argument] than write again all conditions in callback.

wapmorgan avatar Jul 11 '17 23:07 wapmorgan

Thanks, its clear now.

cebe avatar Jul 12 '17 09:07 cebe