如何使用findAll()在yii中编写查询

时间:2014-04-21 12:41:15

标签: php sql yii

我有以下sql查询,如何使用findAll()在yii中编写查询?

我没有使用CDbCriteria并暂时避免使用它。

使用三个表user,category和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%'

我编写了以下查询,但我不知道如何加入:

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

3 个答案:

答案 0 :(得分:3)

$model = JobProfile::model()->with('userrelationname','categoryrelationname')->findAll(array("condition"=>"t.category_id =1 and t.experience =2 and t.key_skills LIKE '%php%'"));

您可以在JobProfile模型中找到关系名称

关系示例

您的JobProfile模型文件中将有源代码,如

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

这是'用户'是关系名称......

然后在您的控制器示例中;

foreach($model as $m){
    echo $m['user_id']; // in your job_profile table
    echo $m->user->id;  // in your user table
}

答案 1 :(得分:2)

您可以将queryAll与create命令一起使用。

    $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();

答案 2 :(得分:0)

你能这样试试吗?

$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);