我是YII框架的新手,我正在尝试使用活动记录和ORM框架。
有三张桌子请检查图像
这是我的Customer,OrderType和Orders的代码
class Customer extends \yii\db\ActiveRecord
{
public static function tableName()
{
return 'Customer';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['id', 'name'], 'required'],
[['id'], 'integer'],
[['name'], 'string'],
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getCustomers()
{
return $this->hasMany(CollectorCustomerMaster::className(), ['CollectorCode' => 'CollectorCode']);;
}
}
<?php
namespace api\modules\v1\models;
use Yii;
class OrderType extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'OrderType';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['id', 'name'], 'required'],
[['id'], 'integer'],
[['name'], 'string'],
];
}
}
class Orders extends \yii\db\ActiveRecord
{
public static function tableName()
{
return 'Orders';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['id', 'name','customer_id','order_type_id'], 'required'],
[['id','customer_id','order_type_id'], 'integer'],
[['name'], 'string'],
];
}
public function getOrderType(){
return $this->hasOne(OrderType::className(), ['id' => 'order_type_id']);
}
}
如果我尝试查询订单类型的订单,订单类型数据不会出现。这是我的代码,
if (Yii::$app->common->checkRequest('POST')) {
//if ($this->validateRoute('getCustomers')) {
$coCollector = Orders::find()->where(['id'=>'1'])->with('orderType')->one();;
if(isset($coCollector)){
$data2 = null;
Yii::$app->common->setCode(200);
$response = ['status' => Yii::$app->common->getCode(), 'message' =>'Success', 'data' =>$coCollector,'data2'=>$data2];
return $response;
}
// }
}
如果运行此命令,则会得到以下结果。
{
"status": 200,
"message": "Success",
"data": {
"id": "1",
"customer_id": "4",
"order_type_id": "1",
"name": "Aptitude "
},
"data2": null
}
如何也获取OrderType数据?请有人帮我。我在互联网上进行了彻底搜索,没有找到任何示例代码。
您已经在Order类中将OrderType关系定义为getOrderType()
函数。因此,您可以使用此关系函数获取OrderType数据。您可以像这样直接在Order类对象上调用此关系函数
$orderTypeData = $coCollector->getOrderType();
或者您可以通过以下简单方式使用它
$orderTypeData = $coCollector->orderType;
。
然后,您可以将其放入您的文件中$response
。请检查此文档以获得更好的理解。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句