gpt4 book ai didi

php - Yii2 从相关模型中获取值(value)

转载 作者:行者123 更新时间:2023-12-02 04:03:29 26 4
gpt4 key购买 nike

我构建了这个 yii2 应用程序,其中有一个名为 Customer 的模型,另一个名为 Order 的模型,其中 customer_id 是 Order 中的外键>.

我创建了一个名为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']);
}
}

这是 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 (['<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="047769706c446c6b7069656d682a676b69" rel="noreferrer noopener nofollow">[email protected]</a>'=>'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,]);
}

最佳答案

您还需要在 Order 模型类中声明关系:

<?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;

关于php - Yii2 从相关模型中获取值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40764805/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com