求助-Yii2的内部联接-试图获取非对象的属性

时间:2019-07-15 08:52:19

标签: php sql yii2

当每个员工都是一个部门的成员时,我试图链接两个表:employee和department。然后,我将使用两个表中的“ department_id”字段,“部门”中的“类型”字段和“部门”中的“节”字段来检索一些信息。在使用原始PHP和SQL之前,我已经完成了此操作,但是现在我必须将其实现到Yii2。

我首先在视图中添加关系。然后,我尝试使用诸如YielJoinWhere等Yii2函数链接这些表。当失败时,我尝试在Yii中执行原始SQL,但这无济于事。

每个摘录都来自视图。

关系:

class Employee extends \yii\db\ActiveRecord{
    public static function tableName(){
        return 'employees';
    }

    public function getDepartments(){
        return $this->hasOne(Departments::className(), ['department_id' => 'department_id']);
    }
}

class Departments extends \yii\db\ActiveRecord{
    public static function tableName(){
        return 'departments';
    }
    public function getEmployee(){
        return $this->hasOne(Employee::className(), ['department_id' => 'department_id']);
    }
}

我尝试重现的SQL行($ dep和$ sec是一些现在不相关的变量):

SELECT DISTINCT departments.type, departments.department FROM departments
 INNER JOIN employees ON department.department_id = employees.department_id
 WHERE departments.department_id = '$dep' AND departments.section = '$sec'

第一次尝试(Yii2函数):

$result = Departments::find()
    ->select(['departments.type', 'departments.department_id'])
    ->innerJoin('employees', '`employees`.`department_id` =  `departments`.`department_id`')
    ->where(['departments.department_id' => $dep])
    ->andwhere(['departments.section' => $sec])
    ->with('employees')
    ->one();

第二次尝试(原始SQL):

$connection = Yii::$app->getDb();
$command = $connection->createCommand("..."); //same as above
$result= $command->queryOne();

最后,我需要检索信息:

$type = $result->type;
//etc.

两次尝试的错误消息相同:

  

尝试获取非对象的属性,当上面的最后一行是   被执行。

0 个答案:

没有答案