Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to export model data and relation model to json with Yii2?

Tags:

json

php

mysql

yii2

Is there a model connected to mysql table:

<?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']);
    }
}

The controller:

.
..
...
    public function actionIndex()
    {
        $searchModel = new Table1Search();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
...
..
.

The 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]);
            }

and it is exactly what I want, but I need relation too. Just to access to user table like it can be done in gridview: 'value' => 'user.username' or something else, but exported to json. But I have no idea how to do

like image 542
Paolovip Avatar asked May 03 '15 21:05

Paolovip


1 Answers

Check out Model::toArray(): http://www.yiiframework.com/doc-2.0/yii-base-arrayabletrait.html#toArray%28%29-detail

Something like this should automatically do what you want:

class Marker {
    public function fields()
    {
        $fields = parent::fields();
        $fields[] = 'user';

        return $fields;
    }
}

$marker->toArray();
like image 187
laszlovl Avatar answered Sep 22 '22 17:09

laszlovl