2016-05-19 72 views
-1

我請求到數據庫:如何使兩個表中選擇yii2

query = new Query(); 

$messages = $query->select(['name', 'message', 'date'])->from(['`user`','`message`'])->where('`user`.id = `message`.id_user AND id_addressee = '.$id.' AND id_user = '.Yii::$app->user->id)->orderBy('date')->all(); 

in view I make a selection like this: 
<?php foreach($messages as $mess): ?> 
      <tr> 
       <td> 
        <?= Html::encode("{$mess->user->name}") ?> 
       </td> 
       <td> 
        <?= Html::encode("{$mess->message}") ?> 
       </td> 
       <td> 
        <?= Html::encode("{$mess->date}") ?> 
       </td> 
      </tr><?php endforeach; ?> 

所有字段都是空的。我究竟做錯了什麼?

+1

「鑑於我做出這樣的選擇:」 看起來不像有效的代碼給我。你是用僞代碼編寫還是在其他地方定義了這些關鍵字? –

回答

0

確保您已聲明關係。

像:

class User extends \yii\db\ActiveRecord 
{ 
    public function rules(){ 
     return [ 
      [['name'], 'string'], 
     ]; 
    } 
    public function getMessage(){ 
     return $this->hasOne(Message::className(), ['user_id' => 'id']); 
    } 
} 

然後:

$record = User::find() 
     ->joinWith('message') 
     ->all();