I am new to Yii2 and new to MVC so im trying to grasp the concept of things. I am trying setup some relational data so it can be viewed correctly. How do i get the output of the view(index.php) to link up and display the ‘population.population_number’ along side the country_name and the country_code?
table "country"
code, name, population
AU, Australia, 10
table "population"
id, population_id, population_number
1, 10, 10264
My model (Country.php)
namespace frontend\models;
use yii\db\ActiveRecord;
class Country extends ActiveRecord
{
}
My Controller (CountryController)
namespace frontend\controllers;
use yii\web\Controller;
use yii\data\Pagination;
use frontend\models\Country;
class CountryController extends Controller
{
public function actionIndex()
{
$query = Country::find();
$pagination = new Pagination([
'defaultPageSize' => 5,
'totalCount' => $query->count(),
]);
$countries = $query->orderBy('name')
->offset($pagination->offset)
->limit($pagination->limit)
->all();
return $this->render('index', [
'countries' => $countries,
'pagination' => $pagination,
]);
}
}
My View (index.php)
use yii\helpers\Html;
use yii\widgets\LinkPager;
?>
<h1>Countries</h1>
<ul>
<?php foreach ($countries as $country): ?>
<li>
<?= Html::encode("{$country->name} ({$country->code})") ?>
</li>
<?php endforeach; ?>
</ul>
<?= LinkPager::widget(['pagination' => $pagination]) ?>