Yii2 - viaTable join返回错误

时间:2016-02-17 13:47:02

标签: php yii2

我正在尝试编写 hasMany 关系,但我收到此错误:

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; 
check the manual that corresponds to your MySQL server version for the right syntax to use near 
'[[licences.id = userKeys.licence_id]] = `licences`.`0` LEFT JOIN `userKeys` `use' at line 1

The SQL being executed was: 
SELECT COUNT(*) FROM `activityLogsUserActivity` 
LEFT JOIN `users` ON `activityLogsUserActivity`.`user_id` = `users`.`id` 
LEFT JOIN `licences` ON `activityLogsUserActivity`.[[licences.id = userKeys.licence_id]] = `licences`.`0` 
LEFT JOIN `userKeys` `userKeys` ON `licences`.`user_id` = `userKeys`.`user_id`

代码:

public function getKeys()
    {
         return $this->hasMany(UserKeys::classname(), ['user_id' => 'user_id'])
            ->select('licences.licenceName, userKeys.*')
            ->from(['userKeys' => UserKeys::tableName()])
            ->viaTable(Licences::tableName(), ['licences.id = userKeys.licence_id']);
    } 

我做错了什么?

1 个答案:

答案 0 :(得分:0)

['licences.id = userKeys.licence_id']

应该是一个键值对,比如

['id' => 'licence_id']

并且没有必要在那里声明表名,看看文档

http://www.yiiframework.com/doc-2.0/yii-db-activequery.html#viaTable()-detail

  

联结表和与$ primaryModel关联的表之间的链接。数组的键表示联结表中的列,值表示$ primaryModel表中的列。