saiyalel
(Saiyalel)
November 13, 2015, 10:20am
1
i have a dairys model, where their is a category (freshian , gurnsey, aryshure etc) and sex(1,2). category is stored as a number(1-5) .
How do i relate the number stored to display the animal eg freshian and sex. i can do a table and store the categories or a public variable. but tables best for sustainability
softark
(Softark)
November 13, 2015, 12:54pm
2
I would write something like this in Dairy model:
class Dairy extends ActiveRecord
{
...
const SEX_MALE = 1;
const SEX_FEMALE = 2;
...
public static function getSexLabels()
{
return [
self::SEX_MALE => 'Male',
self::SEX_FEMALE => 'Female',
];
}
public function getSexLabel()
{
$labels = self::getSexLabels();
if (isset($lables[$this->sex])) {
return $labels[$this->sex];
} else {
return "invalid sex ({$this->sex})";
}
}
...
Then you can use "->sexLabel" to display the sex of the animal.
$models = Dairy::find()->all();
foreach($models as $model) {
echo $model->sex; // displays 1 or 2.
echo $model->sexLabel; // displays "Male" or "Female"
}
As for the category, you can take the same approach, but probably it’s better to create a table for it.
softark
(Softark)
November 14, 2015, 3:14am
3
create category table.
id ... primary key
name ... varchar (freshian, gurnsey, aryshure etc)
You should add a foreign key constraint between ‘dairy’.‘category_id’ and ‘category’.‘id’.
Create Category ActiveRecord model for it.
Declare relations between Dairy and Category.
// Dairy.php
public function getCategory()
{
return $this->hasOne(Category::className(), ['id' => 'category_id']);
}
// Category.php
public function getDairies()
{
return $this->hasMany(Dairy::className(), ['category_id' => 'id']);
}
Gii will help you in 3) and 4).
Then, you can write like this:
$models = Dairy::find()->all();
foreach($models as $model) {
echo $model->category_id; // displays 1, 2, 3, ... etc
echo $model->category->name; // displays "freshian", "gurnsey", "aryshure" ... etc
}