I
I
Isherath2018-09-03 02:09:51
Yii
Isherath, 2018-09-03 02:09:51

ActiveDataProvider and pagination in REST Yii2?

How to generate a server response with pagination in linked data.
There is a certain category and products in this category, you need to return the client (AngularJS) an array with category data (name, id, etc.) and all products of the selected category, while they must be with information about pagination.
Now I have the following code:
The controller to which the client sends a request:

class ProfileController extends ActiveController
{
    //public $vacancy;
    
    public $modelClass = 'app\models\Profile';
    public $serializer = [
        'class' => 'yii\rest\Serializer',
        'collectionEnvelope' => 'items'
    ];
    
    public function behaviors()
    {
        return ArrayHelper::merge(parent::behaviors(), [
            'corsFilter' => [
                'class' => \yii\filters\Cors::className()
            ]
        ]);
    }
    
    public function actionView($creator)
    {
        $query = Profile::find()->where(['user' => $creator]);
            
        
        $provider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'pageSize' => 30
            ]
        ]);
        
        return $provider;
    }
    
}

Model with connection to another ActiveRecord model:
class Profile extends ActiveRecord
{ 
    
    
    public static function tableName()
    {
        return 'profile';
    }
    
    public function fields()
    {
        return ArrayHelper::merge(parent::fields(), [
            'vacancy'
        ]);
    }
    
    public function getVacancy()
    {
        return $this->hasMany(Vacancy::className(), ['creator' => 'user']);
    }
}

The whole thing returns the following to the client:
5b8c6d0bc809b821092339.jpeg
That is, as you can see from the picture, pagination is only for the Profile model, but it is necessary for the Vacancy model. How to do it right?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Timofeev, 2018-09-03
@Isherath

you took
And passed it to the provider, he returned you the pagination for the Profile, but you wanted him to return something else? Pass something else will return something else.
Maybe you want getVacancy() to return the dataProvider for the Vacancy, then make a method that returns the dataProvider for the Vacancy, like getVacancyDataPrivider().
But it seems to me that it's not worth returning $provider itself, but $provider->models

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question