Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/251.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何使用Yii2将模型数据和关系模型导出到json?_Php_Mysql_Json_Yii2 - Fatal编程技术网

Php 如何使用Yii2将模型数据和关系模型导出到json?

Php 如何使用Yii2将模型数据和关系模型导出到json?,php,mysql,json,yii2,Php,Mysql,Json,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

是否有连接到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']);
    }
}
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]);
            }

//有了它,我可以从db表中获取所有记录:
var-datac=;
对于(变量i=0;i

这正是我想要的,但我也需要关系。只需像在gridview中一样访问用户表:'value'=>'user.username'或其他内容,但导出为json。但是我不知道怎么做

查看
Model::toArray()

类似这样的操作会自动执行您想要的操作:

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

        return $fields;
    }
}

$marker->toArray();

啊,是的!超级简单:$items=\app\models\Model::find()->with(['user'])->asArray()->all();非常感谢。
class Marker {
    public function fields()
    {
        $fields = parent::fields();
        $fields[] = 'user';

        return $fields;
    }
}

$marker->toArray();