2017-02-27 39 views
1

我有表userprofile, 一個用戶擁有最大一個配置文件, 並通過USER_ID和輪廓表名規定。 我不使用外鍵。如何在模型關係鍵中指定值?

我之所以這樣做,是因爲我有其他的表像company也使用表profile,因此利用相關的表和關係relation_id =主鍵=表名指定的參考

profile 
    relation_id 
    relation 

我想實現的是設置模型關係等於字符串的用戶,因此不存在使用鍵,而是改用值。

user.php的

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

錯誤我得到:

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` 

這是產生的GridView因此SQL上計數失敗第一,但錯誤將是select *

相同

SQL我想達到

SELECT * 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 `profile`.`relation` = 'user' 

所以問題是,如何在模型關係鍵中指定值?

回答

2

如果您的用戶有輪廓的關係hasOne應該只使用

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

    } 
+0

但是我用表'profile'像其他表' company'等 – Ripper

+0

,那麼你需要他人的關係的剖面模型 – scaisEdge

+0

我加入SQL我想實現的,請立即檢查 – Ripper