Thursday, 28 March 2019

Yii database model

This is partly based on the documentation found at


If you're going to work with records using Yii, it's helpful to make use of the ActiveRecord class. In this example, we're working with a database of country data.  Thankfully, this is a simple scenario which requires the creation of a simple class. Just add this as models/Country.php
namespace app\models;
use yii\db\ActiveRecord;
class Country extends ActiveRecord


Next we need to create a controller which we can use to pass data from the Country ActiveRecord model to a view. In this case, we're also going to add some pagination functionality, which we'll also pass to the view.

  1. First we create a $query object which will be used to retrieve the data.
  2. Next we create a $pagination object which will be used to control the display of that data.
  3. Next we get all the data we want.
  4. Finally we pass the data and pagination objects to the view.

We save this class as controllers/CountryController.php

namespace app\controllers;
use yii\web\Controller;
use yii\data\Pagination;
use app\models\Country;
class CountryController extends Controller
    public function actionIndex()
        $query = Country::find();
        $pagination = new Pagination([
            'defaultPageSize' => 5,
            'totalCount' => $query->count(),

        $countries = $query->orderBy('name')

        return $this->render('index', [
            'countries' => $countries,
            'pagination' => $pagination,


The view performs 3 tasks in this process:
Loops through the data, adding it to the page.
Adding the pagination object to that the data can be paged through.
Adding the LinkPager widget object to the pagination object to automatically create all those links, saving us a bunch of coding.
We'll put the view in the directory views/country/index.php

use yii\helpers\Html;
use yii\widgets\LinkPager;
<?php foreach ($countries as $country): ?>
        <?php echo Html::encode("{$country->code} ({$country->name})"); ?>:
        <?php echo $country->population; ?>
<?php endforeach; ?>
<?php echo LinkPager::widget(['pagination' => $pagination]); ?>

No comments:

Post a Comment