我想将MongoDB用户收集数据显示到yii2 tablle中。当我运行时,它不会显示任何数据输出,only show 5 empty rows(我的用户集合中有5行)
我是mongodb中的新手。我尝试使用通常的格式来显示它,因为我显示的是来自mysql的数据(仅更改了查询)。它似乎不能很好地工作,但不会显示任何错误消息
这是我的代码:
Model / User.php
class User extends ActiveRecord implements IdentityInterface
{
public $_id;
public $username;
public $password;
public static function collectionName()
{ return ['latihan', 'User']; }
public function attributes()
{
return [
'_id',
'id',
'username',
'password',
'role',
];
}
public function fields()
{
return [
'_id' => function() { return (string)$this->_id; },
'id',
'username',
'password',
'role',
];
}
public function rules()
{
return [
['role', 'default', 'value' => 10],
[['_id', 'username', 'password'], 'safe'],
];
}
public static function findOne($condition)
{
$query = new Query();
$data = $query->from(static::collectionName())->where($condition)->one();
$user = new User();
$user->id = $data['id'];
$user->username = $data['username'];
$user->password = $data['password'];
$user->role = $data['role'];
return $user;
}
HomeController.php
public function actionAbout()
{
$user = User::find()->all();
return $this->render('about', ['model' => $user]);
}
}
About.php
<table class="table table-bordered">
<thead>
<tr>
<th>#</th>
<th>Username</th>
<th>Password</th>
<th>Aksi</th>
</tr>
</thead>
<tbody>
<?php $i = 1; foreach($model as $field){ ?>
<tr>
<?php $username =$field->username; ?>
<td><?php echo $i++; ?></td>
<td><?= $field->username; ?></td>
<td><?= $field->password; ?></td>
<td>
<a href="<?php echo Url::to(['/home/editabout']).'?id='.$field->id;?>"> Update</a> |
<a href="<?php echo Url::to(['/home/deleteabout']).'?id='.$field->id; ?>"> Delete</a>
</td>
</tr>
<?php } ?>
</tbody>
</table>
答案 0 :(得分:-1)
来自this question 首先,您必须添加 yii2-mongodb在composer.json文件中,并使用此命令 composer update
更新composer然后,您可以编辑 main-local.php 文件并覆盖 db 组件。
return [
//....
'components' => [
'db' => [
'class' => '\yii\mongodb\Connection',
'dsn' => 'mongodb://@localhost:27017/mydatabase',
'options' => [
"username" => "Username",
"password" => "Password"
]
],
],
];
+ 如果要同时使用mysql(默认连接)和mongodb,则必须不覆盖 db 组件,而只需添加mongodb。
return [
//....
'components' => [
'db' => [
.... mysql db config (default)
],
'mongodb' => [
'class' => '\yii\mongodb\Connection',
'dsn' => 'mongodb://@localhost:27017/mydatabase',
'options' => [
"username" => "Username",
"password" => "Password"
]
],
],
];