[英]How to export model data and relation model to json with Yii2?
是否有連接到mysql表的模型:
<?php
namespace app\models;
use Yii;
use my_model\yii2\user\models\User;
/**
* 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 \yii\db\ActiveRecord
{
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 yii\widgets\ListView;
use yii\helpers\Html;
use my_model\yii2\user\models\User;
$this->title = 'table1';
use yii\web\IdentityInterface;
?>
<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 Model::toArray()
這樣的東西應該自動做你想要的:
class Marker {
public function fields()
{
$fields = parent::fields();
$fields[] = 'user';
return $fields;
}
}
$marker->toArray();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.