2016-04-05 4 views
0

クエリに関係を取得する方法Yii2とのActiveRecord:私はYii2に新しいですし、私はこれを行う必要があり

を私は2つのテーブルがあります。 表: tbl_user フィールド: USER_IDは、

をlast_company_id

データ: のuser_id = 29 last_company_id = 49

表: tbl_user_subscriber_company: フィールド: USER_ID、のcompany_id、current_module

データ: のuser_id = 29、 のcompany_id = 49、 current_module = 'モジュールA'

user_id = 29, 
company_id = 50, 
current_module = 'Module B' 

I Userモデルを呼び出すことによって、userおよびlast_company_idのcurrent_moduleを取得する必要があります。 (私は、彼らは、データベースからそれに関連するすべてのフィールドを持つユーザモデルからユーザオブジェクトを構築し、働いている会社の要件)

だから私は、このMySQLのクエリを変換したい:

select current_module 
from tbl_user a 
RIGHT JOIN tbl_user_subscriber_company b 
ON a.user_id = b.user_id 
AND a.last_company_id = b.company_id 
where a.last_company_id = 49 
and a.user_id = 29 

Uselモデルのyii2 ActiveRecordへ

私は、選択されたユーザーとそのlast_company_idのユーザーの現在のモジュールを返すgetCurrentmoduleという関数を用意する必要があります。

希望私は理解するのが少し難しいです。例えば

+0

参照してください。http://stackoverflow.com/questions/ 29447538/how-to-use-join-in-yii2-active-record-for-relational-model –

答えて

1

は私はわからないが、あなたのような何かを試すことができます。

User::find() 
    ->joinwith('tbl_user_subscriber_company',true,'RIGHT JOIN') 
    ->select(['current_module']) 
    ->where(['user_id' => tbl_user_subscriber_company.user_id]) 
    ->andWhere(['last_company_id' => tbl_user_subscriber_company.company_id]) 
    ->andWhere(['last_company_id' => 49]) 
    ->andWhere(['user_id' => 29]) 
    ->all(); 

OR

$data = (new \yii\db\Query()) 
     ->select('current_module') 
     ->from('tbl_user user') 
     ->rightJoin('tbl_user_subscriber_company usc','user.user_id = user_id') 
     ->where('user.last_company_id = usc.company_id') 
     ->andWhere('user.last_company_id = 49') 
     ->andWhere('user.user_id = 29') 
     ->all(); 
+0

@Insane Skullありがとうございます。私は雇用主に、仕事をする前にyiiを学ぶ時間が必要だと確信しました。すぐにあなたのコードを試し、あなたに知らせるでしょう。 @SigalZahavi。 –

+0

。大丈夫、あなたの時間とすべての最高の仲間を取る。 –

関連する問題