How to export model data and relationship model to json with 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']);
    }
}

      

Controller:

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

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

      

Php index:

<!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 that's exactly what I want, but I need an attitude too. Just to access the user table, as can be done in the gridview: 'value' => 'user.username' or whatever, but exported to json. But I have no idea how to do it.

+3


source to share


1 answer


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();

      

+6


source







All Articles