Skip to content

Feature request: DataProvider for related models #977

@alpharder

Description

@alpharder

Dear developers!
Yii lacked of this functionality, but in my opinion this is very basic thing which is very often needed. So much hope to see it at Yii2 release.

Suppose we have two entities: "Blog" and "Subscriber", their relations between each other are:

  • Blog MANY_MANY Subscribers;
  • Subscriber MANY_MANY Blog;

It is very easy to fetch all of the subscribers of concrete blog:

$subscribers= $blog->subscribers;

Problem:

But when we want to use pagination together with other charms of CListView or CGridView, the easiest way is CActiveDataProvider.

Currently available solution

In this case, we have to write monstrous piece of code every time:

$blog = Blog::model()->findByPk(1);

$dataProvider = new CActiveDataProvider(Subscriber::model(), array(
    'criteria' => array(
         'with'     => array(
                'blogs' => array(
                      'select' => false,
                      'joinType' => 'INNER JOIN',
                      'on'       => 'blogs.id = :currentBlogID',
                      'params'   => array(':currentBlogID' => $blog->id)
                 )
         ),
         'together' => true
)));

I think this could come as a part of framework, probably like this:

$blog = Blog::model()->findByPk(1);

$config = array('pagination'=>array('pageSize'=>20));

$dataProvider = CActiveDataProvider::createForRelation(
        array($blog, 'subscribers'),
        $config
);

I think this method could easily programmaticaly generate criteria of retrieving related records for both MANY_MANY and HAS_MANY relation types.
Unfortunately, I'm not very familiar with code of CActiveFinder and CJoinElement, but I'm pretty sure they do the same work while generating SQL for eager-loading of related records. So, probably, they can be used for this purpose.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions