如何在模型关系键中指定值?

时间:2017-02-27 19:40:48

标签: yii2

我有表格Buser, 一个用户最多有一个个人资料, 并在个人资料中由 user_id 表名指定。 我不在那里使用外键。

我这样做的原因是因为我有其他表profile也使用表company,所以引用由 relation_id =相关表的主键 relation =表名

profile

我想要实现的是将模型关系设置为等于字符串用户,所以不要在那里使用键,而是使用值。

user.php的

profile 
    relation_id
    relation

错误我明白了:

public function getProfile()
{
    return $this->hasOne(Profile::className(),
        ['relation_id' => 'user_id', 'relation' => User::tableName()]);
}

它用于生成GridView,因此sql首先计数失败,但SQLSTATE[42S22]: Column not found: 1054 Unknown column 'user.user' in 'on clause' The SQL being executed was: SELECT COUNT(*) FROM `user_login` LEFT JOIN `user` ON `user_login`.`user_id` = `user`.`user_id` LEFT JOIN `profile` ON `user`.`user_id` = `profile`.`relation_id` AND `user`.`user` = `profile`.`relation`

的错误相同

SQL我想实现

select *

所以问题是,如何在模型关系键中指定值?

1 个答案:

答案 0 :(得分:2)

如果您的用户与配置文件有关系,则应仅使用

public function getProfile()
{
   return $this->hasOne(Profile::className(),
    ['relation_id' => 'user_id']);
}

如果您需要使用

  public function getProfile()
  {
     return $this->hasOne(Profile::className(),
      ['relation_id' => 'user_id'])->andOnCondition(['relation' => User::tableName()]);

  }