简体   繁体   中英

Yii2 Get Value from Related Model

I have built this yii2 app where I have a model named Customer , and another named Order , where customer_id is the foreign key in Order .

I have created an action named SendEmail , which is used in the Order index page, and I need to get the email which the order will be sent to according to the customer_id.

So how can I get the email for the current Order according to the Customer ?

Customer Model:

<?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']);
}
}

And here is the action in the controller:

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 (['smth@hotmail.com'=>'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,]);
    } 

You need to also declare the relationship in your Order model class:

<?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']);
    }
}

This way you can just get the email like this:

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

If you define relations in your models, which in this case did, you can access the related data using relations easily either from customs to orders or vise o versa.

All you need to do is to access relation from the instance of model to the related model as a property. For example if you have got costumer instance and need the orders you do this:

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

(Note that the i above is the index of customer's demanded order because the relation is one to many and customer may have multiple orders.)

And if you have one of the orders and you need to access the customer that ordered it you do this:

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

PS: It is always a good practice to define relations in both of your models and in this case define it in both customer and order models.

You can understand relations and their definitions in Yii2 by taking a look at This Document .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM