0

What is the equivalent code in Yii?

while($row = mysql_fetch_assoc)
{
echo $row['id']." ".getSkillById($row['skillId']);
}  

function getSkillById($id)  
{
$sql = mysql_query("select * from `skills` WHERE id = '$id'");
$res = mysql_fetch_assoc($sql);
return $res['skill_label'];
}

How can something be implemented in yii?
Is this standard procedure?

0

1 Answer 1

2

ActiveRecord approche:

First, Create your model by using GII. for example your model name is: Skill. Now:

$skills=Skill::findAll();
if(!is_null($skills)){
   foreach($skiils as $skill){
        echo $skill->id;
   }
}

To get an skill by ID:

$skill=Skill::findByPk($id);
$skill->id; // Gets the skill ID

Woww, Don't you know Yii's AR supports Relations? Assume that you have a User table that each user has an skill id. So you must create User model. then in your relation() method of your user model you must write:

array('skill'=>array(self::HAS_ONE,'Skill','skill_id'));

All above are based on assumption. (AS YOUR QUESTION IS A LITTLE BROAD).Now, You can access to your users and their's skill by:

$users=User::findAll();
if(!is_null($users)){
   foreach($users as $user){
        echo $user->id; // USER IS
        echo $user->skill->id; // USER SKILL ID
   }
}

Another approach is using Yii's query builder like below:

$db=Yii::app()->db;
$skills=$db->createCommand('SELECT * FROM tbl_skills')->queryAll();
// A LOOP
// foreach($skills as $skill) -> now the result is an associate array.

As a suggestion, first read carefully about Yii's ORM (AR) and Yii's Query Builder. Best place to find useful information is Yii's official document:

Active Record

Query Builder

Sign up to request clarification or add additional context in comments.

2 Comments

Relations is a best method ,but i can't use it,because i am using "query builder"
So you can use Join in query builder or write your sql in query builder with a JOIN and use it easily

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.