php – 如何使用Yii2将模型数据和关系模型导出到json?
发布时间:2020-12-13 17:48:36 所属栏目:PHP教程 来源:网络整理
导读:是否有连接到 mysql表的模型: ?phpnamespace appmodels;use Yii;use my_modelyii2usermodelsUser;/** * This is the model class for table "table1". * * @property string $id * @property string $name * @property string $description * @propert
是否有连接到
mysql表的模型:
<?php namespace appmodels; use Yii; use my_modelyii2usermodelsUser; /** * This is the model class for table "table1". * * @property string $id * @property string $name * @property string $description * @property double $data1 * @property double $data2 */ class Marker extends yiidbActiveRecord { public static function tableName() { return 'table1'; } public function rules() { return [ [['name',],'required'],... .. . ]; } public function attributeLabels() { return [ 'id' => Yii::t('app','ID'),'name' => Yii::t('app','Name'),... .. . ]; } public function getUser() { return $this->hasOne(User::className(),['id' => 'userid']); } } 控制器: . .. ... public function actionIndex() { $searchModel = new Table1Search(); $dataProvider = $searchModel->search(Yii::$app->request->queryParams); return $this->render('index',[ 'searchModel' => $searchModel,'dataProvider' => $dataProvider,]); } ... .. . index.php: <!DOCTYPE html> <?php use yiiwidgetsListView; use yiihelpersHtml; use my_modelyii2usermodelsUser; $this->title = 'table1'; use yiiwebIdentityInterface; ?> <head> <script> //with this I can get all the record from db table: var datac = <?php echo json_encode($model) ?>; for (var i = 0; i < datac.length; i++) { displayLocation(datac[i]); console.log(datac[i]); } 这正是我想要的,但我也需要关系.只需访问用户表就像在gridview中一样:’value’=> ‘user.username’或其他,但导出到json.但我不知道该怎么做 解决方法
查看Model :: toArray():
http://www.yiiframework.com/doc-2.0/yii-base-arrayabletrait.html#toArray%28%29-detail
这样的东西应该自动做你想要的: class Marker { public function fields() { $fields = parent::fields(); $fields[] = 'user'; return $fields; } } $marker->toArray(); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |