2016-11-23 41 views
0

我已經建立了這個yii2應用,在那裏我有一個型號命名客戶獲得值,和另一個名爲訂購,其中CUSTOMER_ID是訂購外鍵。Yii2從相關型號

我已經創建了一個名爲SendEmail的動作,這是在訂單索引頁使用,我需要得到的訂單將會被髮送到根據CUSTOMER_ID的電子郵件。

所以,我怎麼能得到根據客戶當前訂購的電子郵件?

客戶型號:

<?php 

namespace app\models; 

use Yii; 

class Customer extends \yii\db\ActiveRecord 
{ 
    /** 
    * @inheritdoc 
    */ 
    public static function tableName() 
    { 
     return 'customer'; 
    } 
public function rules() 
{ 
    return [ 
     [['Name'], 'required'], 
     [['Archive', 'Credit'], 'integer'], 
     [['Address'], 'string'], 
     [['Name', 'Email'], 'string', 'max' => 50], 
     [['Tel'], 'string', 'max' => 14], 
     [['Category'], 'string', 'max' => 25], 
    ]; 
} 

/** 
* @inheritdoc 
*/ 
public function attributeLabels() 
{ 
    return [ 
     'Id' => 'ID', 
     'Name' => 'Name', 
     'Tel' => 'Tel', 
     'Email' => 'Email', 
     'Archive' => 'Archive', 
     'Credit' => 'Credit', 
     'Address' => 'Address', 
     'Category' => 'Category' 
    ]; 
} 

/** 
* @return \yii\db\ActiveQuery 
*/ 
public function getOrders() 
{ 
    return $this->hasMany(Order::className(), ['Customer_Id' => 'Id']); 
} 
} 

這裏是在控制器中的作用:

public function actionSendEmail($id) 
{ 
    //Here I should get the email according to the customer_id 

    if ($model->load(Yii::$app->request->post())) 
    { 

      $value= Yii::$app->mailer->compose() 
      ->setFrom (['[email protected]'=>'Smth']) 
      ->setTo ($model->Email) 
      ->setSubject ("Price Offer") 
      ->setHtmlBody ("Test") 
      ->send(); 

     $model->save(); 
     return $this->redirect(['view','id'=>$model->id]);} 
     else 
      return $this -> render('create',['model'=>$model,]); 
    } 
+0

您是否定義了Yii 2中兩個模型之間的關係? – Bizley

+0

是的,我確實做到了。 –

+0

那麼究竟是什麼問題呢?你有關係,你可以獲取模型並獲得客戶的電子郵件。 – Bizley

回答

1

您還需要申報您的訂單模型類的關係:

<?php 

namespace app\models; 

use Yii; 

class Order extends \yii\db\ActiveRecord 
{ 
    ... Some code here ... 

    /** 
    * @return \yii\db\ActiveQuery 
    */ 
    public function getCustomer() 
    { 
     return $this->hasOne(Customer::className(), ['Id' => 'Customer_Id']); 
    } 
} 

這樣你就可以得到這樣的電子郵件:

$email = $order->customer->Email; 
0

如果您在您的模型中定義了關係,在這種情況下,您可以使用關係輕鬆訪問相關數據,無論是從訂單到訂單還是反之亦然。

您只需要將模型實例與相關模型的關係作爲屬性進行訪問。 例如,如果你有負荷消費實例,並需要你這樣做的命令:

$customer->orders[i]->[property or method of the related model you demand access] 

(請注意,上述i是客戶的要求順序的索引,因爲關係是one to many和客戶可能有多個訂單)

如果你有訂單之一,你需要訪問下令客戶你這樣做:

$order->customer->[property or method of the related model you demand access] 

PS:它始終是一個很好的做法,來定義關係您的兩款車型都會在customerorder車型中進行定義。

您可以通過查看This Document瞭解Yii2中的關係及其定義。