是否有模型连接到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'=&gt; 'user.username'或其他,但导出到json。但我不知道该怎么做
答案 0 :(得分:7)
结帐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();