所以我正在与Yii2一起工作,我正在设法使我认为的关系数据库井然有序。我想做的是使用Yii2 rest api让多个表返回一组数据。
香港专业教育学院一直试图找到确切我需要做什么,但我有点困惑。我相信我必须设置外键并以某种方式链接它们,但这就是我迷路的地方。我也认为,一旦数据库部分设置好,当我建立一个新模型时,gii工具是否会处理“关系”?我认为我必须手动构建新的模型/控制器而不是使用gii,后者会将所有模板发送到“ frontend”目录而不是我的版本化“ module / v1”目录
----编辑更改----
表“状态”:
- country_id is the index
+--------------------------------------+---------------------------------+
| Column | Internal Relations | Foreign Key constraint (INNODB) |
+--------------------------------------+---------------------------------+
| country_id | yii2.country.country_id | yii2.ountry.country_id |
+------------------------------------------------------------------------+
+-------------+------------------+----------------------+
| id (int, AI)| country_id (int) | state_name (varchar) |
+-------------+------------------+----------------------+
| 0 | 10 | Texas |
| 1 | 10 | New York |
| 2 | 20 | Glasgow |
+-------------+------------------+----------------------+
表“国家”:
- country_id is the Primary Key
- column to display in relation-view is country_name
+------------------+--------------------------+
| country_id (int) | country_name (varchar) |
+------------------+--------------------------+
| 10 | United States of America |
| 20 | Germany |
+------------------+--------------------------+
所以我的目标是让我的api GET请求:
localhost/yii2/api/web/vi/states/
并得到以下回应:
{
“成功”:是的,
“数据”:[
{
“ id”:1
“ country_id”:10,
“ state_name”:“得克萨斯州”
},
{
“ id”:2
“ country_id”:10,
“ state_name”:“纽约”
},
{
“ id”:3,
“ country_id”:20,
“ state_name”:“格拉斯哥”
}
]
}
}
模型(State.php):
<?php
namespace api\modules\v1\models;
use Yii;
/**
* This is the model class for table "state".
*
* @property integer $country_id
* @property string $state_name
*
* @property Country $country
*/
class State extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'state';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['country_id', 'state_name'], 'required'],
[['country_id'], 'integer'],
[['state_name'], 'string', 'max' => 55]
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'country_id' => 'Country ID',
'state_name' => 'State Name',
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getCountry()
{
return $this->hasOne(Country::className(), ['country_id' => 'country_id']);
}
}
控制器(StateController.php):
<?php
namespace api\modules\v1\controllers;
use yii\rest\ActiveController;
/**
* Country Controller API
*
*/
class StateController extends ActiveController
{
public $modelClass = 'api\modules\v1\models\State';
}
最佳答案
在数据库中设置外键并使用gii生成模型,它将根据您的关系自动链接它们,然后您可以像这样使用它...
$states= State::find()->with('countries')->all();
此代码将使您获得所在国家的州