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

标签 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 $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,
        ]);
    }
...
..
.

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

关于php - 如何使用 Yii2 将模型数据和关系模型导出到 json?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30019495/

相关文章:

php - 在 Mac 上安装了 PHP 7.3,但它仍然呈现 7.1.23

php - 为什么查询在 mysql 中有效,prepare 语句有效,但 bind_param 无效?

javascript - 从mysql结果数组中获取值

ios - Object Swift 中数组中的对象

MYSQL - 在选择器中但得到所有

javascript - 使用 JSON 值提供 SELECT 并设置所选值

php - 如何在 PHP 中使用命名空间实现类

javascript - Summernote - 验证时显示为原始 HTML 的文本

php - 如何让多个开源网络应用程序使用同一个数据库

mysql - 处理表格的困境?