Hey Guys! 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
How can I do what I need?
I Hope you guys can help me, as I said I’m new.
Thanks in advance!