How to write the query in yii,using findAll()

2019-03-06 00:45发布

I have the following sql query, how can I write the query in yii using findAll()?

I am not using CDbCriteria and for the time being avoiding it.

Using three tables user, category and job_profile.

SELECT * 
FROM job_profile
INNER JOIN user ON user.id = job_profile.user_id
INNER JOIN category ON category.id = job_profile.category_id
WHERE category_id = 1
  AND experience = 2
  AND key_skills LIKE  '%php%'

I have written the following queries but I do not know how to include join:

 $results = SearchEmployee::model()->findAll("category_id=:category AND key_skills like 
:skill AND experience=:experience", array(
            'category'=>$category,
            'skill'=>'%'.$skills.'%',
            'experience'=>$experience
            ));        

标签: php sql yii
3条回答
聊天终结者
2楼-- · 2019-03-06 01:02

you can use queryAll with create command.

    $query= " SELECT * 
    FROM job_profile
    INNER JOIN user ON user.id = job_profile.user_id
    INNER JOIN category ON category.id = job_profile.category_id
    WHERE category_id =1
    AND experience =2
    AND key_skills LIKE  '%php%'";

                $result= Yii::app()->db->createCommand($query)->queryAll();
查看更多
来,给爷笑一个
3楼-- · 2019-03-06 01:11
$model = JobProfile::model()->with('userrelationname','categoryrelationname')->findAll(array("condition"=>"t.category_id =1 and t.experience =2 and t.key_skills LIKE '%php%'"));

You can find relations names in your JobProfile model

Example for relations

There will be source code in your JobProfile Model File like

 public function relations(){
    return array(
      'user' => array (self::BELONGS_TO, 'User', 'id' ),
    )
 }

Here is 'user' is relation name...

then in your controller example;

foreach($model as $m){
    echo $m['user_id']; // in your job_profile table
    echo $m->user->id;  // in your user table
}
查看更多
放荡不羁爱自由
4楼-- · 2019-03-06 01:12

Can you try this way:

$c = array('join' => 
    array(
        'user' => array(
            'joinType' => 'INNER JOIN',
            'on' => 'user.id = t.user_id'
        ),
        'category' => array(
            'joinType' => 'INNER JOIN',
            'on' => 'category.id = t.category_id'
        ),
    ),
    'condition' => "t.category_id =1 and t.experience =2 and t.key_skills LIKE '%php%'"
);
$results = SearchEmployee::model()->findAll($c);
查看更多
登录 后发表回答