Displaying data from 2 tables

Hey Guys! :grinning: Im relatively new to PHP and Yii Framework 2 but I’ve put a lot of effort since I started.
Im having trouble with ActiveRecord model classes, Relations and displaying data in Views.

I got this 2 models, Curso and Profesor. Yes! My code is in spanish!
Both extend from ActiveRecord and has one-to-one relations methods as seen below.

class Curso extends ActiveRecord
{ …
public function relations()
{
return array(
‘profesor’ => array(self::HAS_ONE, ‘Profesor’, ‘curso_id’),
);
}
}


class Profesor extends ActiveRecord
{ …
public function relations()
{
return array(
‘curso’ => array(self::BELONG_TO, ‘Curso’, ‘profesor_id’),
);
}
}


Here are the two tables:
Curso

id PK varchar
profesor_id FK int
cant_alumnos int
cant_hombres int
cant_mujeres int
cant_repitentes


Profesor

id PK int
nombre varchar
primer_apellido varchar
segundo_apellido varchar
rut varchar
fono varchar
direccion varchar
email varchar
curso_id FK varchar


I need to display profesor->nombre and profesor->primer_apellido in a table instead of profesor_id.

Here’s my controller:

class CursoController extends Controller
{ …
public function actionVer()
{
$form = new CursoSearch();
$search = null;
if($form->load(Yii::$app->request->get()))
{
if($form->validate())
{
$search = Html::encode($form->q);
$table = Curso::find()
->where([“like”, “id”, $search]);
$count = clone $table;
$pages = new Pagination([
“pageSize” => 1,
“totalCount” => $count->count()
]);
$model = $table
->offset($pages->offset)
->limit($pages->limit)
->all();
}
else
{
$form->getErrors();
}
}
else
{
$table = Curso::find();
$count = clone $table;
$pages = new Pagination([
“pageSize” => 1,
“totalCount” => $count->count(),
]);
$model = $table
->offset($pages->offset)
->limit($pages->limit)
->all();
}
return $this->render(“ver”, [“model” => $model, “form” => $form,
“search” => $search, “pages” => $pages]);
}
}


I don’t know what else to do. I also don’t know how to make the views (ver.php) show the related table data.

Here’s a Screenshot of my view ver.php

Captura2

How can I do what I need?

I Hope you guys can help me, as I said I’m new.

Thanks in advance! :grin:

you should read this
https://www.yiiframework.com/wiki/653/displaying-sorting-and-filtering-model-relations-on-a-gridview

These definitions of the relations are written in Yii 1.1 syntax. You should follow Yii 2.0 syntax.

Guide > Active Record > Working with Relational Data
https://www.yiiframework.com/doc/guide/2.0/en/db-active-record#relational-data

I also want to recommend you to try “Gii”, the extremely helpful code generator of Yii. It will automatically generate the model code of “Curso” and “Profesor” properly, including the declarations of the relations between them, just in a couple of minutes by reading the table schema of “curso” and “profesor”. It can also create a standard CRUD code for you. Just try it, and you’ll like it.

Guide > Getting Started > Generating Code with Gii
https://www.yiiframework.com/doc/guide/2.0/en/start-gii

Seems accurate. Thanks man but I still don’t understand.

The wiki tells me to write a CursoSearch class that extends Curso, but my CursoSearch class seems to be different.

class CursoSearch extends model
{
public $q;

public function rules()
{
    return [
        ["q", "match", "pattern" => "/^[0-9a-d°\s]+$/i ", "message" => "Sólo se aceptan letras y numeros"]
    ];
}
public function attributeLabels()
{
    return [
        'q' => "Buscar:",
    ];
}

}

Should I write a new one?

After setting up the model they said

“Now we will be able to setup our GridView so to display the related data:”

// ... more grid configuration here
 'columns' => [
 // ... more columns configuration here
 [
 'attribute' => 'city',
 'value' => 'city.name'
 ],
 [
 'attribute' => 'country',
 'value' => 'country.name'
 ],
 // ... more stuff here

Is that part of the model? If not where do I put that code?

Thank you I didn’t know. I was very confused between relations and getters.

The wiki assumes that you have created CRUD code using Gii, and tries to describe how to modify the code in order to handle the relation.

A search model (CursoSearch in your case) in the wiki has been originally created by Gii’s CRUD generator. So it’s different from yours. Your CursoSearch is a simple container of a query parameter, while the one created by Gii is a container of the query parameters and a utility to construct the sql query. Its “search” method returns an “ActiveDataProvider” that provides the rows of data to a “GridView” or “ListView”. It also handles OFFSET and LIMIT for you.

The definitions of the ‘columns’ is for a GridView.

I finally did it with this guide. Thank you again!

You helped a lot. I changed my code to gii generated code and I finally did it. Thanks!

1 Like

It’s great to have a feedback from you. I’m glad that I could help you a little.:+1: