Model relation to DataProvider

I’m having a problem that probably have a simple solution. In my website a user can have multiple followers, I want to list that followers using a ListView

To access to all followers from a user I can do someting like this:




$user = \common\models\User::findOne(['username' => $username]);

if($user === null)

     throw new NotFoundHttpException(Yii::t('app', 'The requested page does not exist.'));


$followers = $user->followers;



But now I must create a dataprovider to pass to the ListView widget, how can I do this?

Hi,

Not tested…

Try this:




$user = User::findOne(1);


$followerDataProvider = new ActiveDataProvider([ 

        'query' => $user->followers

]);



Regards

I bet for




$user = User::findOne(1);


$followerDataProvider = new ActiveDataProvider([ 

        'query' => $user->getFollowers()

]);



no tested :D but getFollowers return a \yii\db\ActiveQuery instance

Aaaand … you are absolutely correct. ;)

Thanks for the correction. ;)

Thank you for your examples, my first approach was exactly this




$user = User::findOne(1);


$followerDataProvider = new ActiveDataProvider([ 

        'query' => $user->followers

]);



This not work. Then I figured that this also work:




$user = User::findOne(1);


$followerDataProvider = new ActiveDataProvider([ 

        'models' => $user->followers

]);



But I like more your solution Bushi…

Thank you!