我正在玩yii2和mongodb,我被困在一个点上。我使用mongodb GII创建了CRUD功能。现在我正在修改将数组的对象放在我的数据库记录中。
在创建客户时,我会创建一个里程对象并按此推送。
$model = new Customer();
if ($model->load(Yii::$app->request->post())) {
$mileage = new mileage(2, 'British Airways', 'Usman', 10000);
$model->mileage = array($mileage);
$model->save();
return $this->redirect(['view', 'id' => (string) $model->_id]);
}
mileage.php
class Mileage {
public $_id;
public $sm_order_id;
public $program;
public $customer;
public $miles;
public function __construct($sm_order_id, $program, $customer, $miles) {
$this->_id = new \MongoId();
$this->sm_order_id = $sm_order_id;
$this->program = $program;
$this->customer = $customer;
$this->miles = $miles;
}
}
我在数据库中获得以下格式的数据:
array (
'_id' =>
MongoId::__set_state(array(
'$id' => '569cd9ed9eb8954c2000002c',
)),
'name' => 'Alan',
'email' => 'alan@abc.com',
'address' => 'New York',
'mileage' =>
array (
0 =>
array (
'_id' =>
MongoId::__set_state(array(
'$id' => '569cd9ed9eb8954c2000002b',
)),
'sm_order_id' => 2,
'program' => 'British Airways',
'customer' => 'Wake',
'miles' => 10000,
),
),
)
现在我想要一个机制,这样我就可以在里程节点中添加更多数组/对象。我搜索了很多,但没有找到任何东西。下面提到了相同的数据库格式:
array (
'_id' =>
MongoId::__set_state(array(
'$id' => '569cd9ed9eb8954c2000002c',
)),
'name' => 'Alan',
'email' => 'alan@abc.com',
'address' => 'New York',
'mileage' =>
array (
0 =>
array (
'_id' =>
MongoId::__set_state(array(
'$id' => '569cd9ed9eb8954c2000002b',
)),
'sm_order_id' => 2,
'program' => 'British Airways',
'customer' => 'Wake',
'miles' => 5000,
),
1 =>
array (
'_id' =>
MongoId::__set_state(array(
'$id' => '569cd9ed9eb8954c2000002c',
)),
'sm_order_id' => 7,
'program' => 'Qatar Airways',
'customer' => 'Tony',
'miles' => 2500,
),
),
2 =>
array (
.........
.........
),
)
答案 0 :(得分:2)
好的,我很久以前就找到了解决方案,我想我应该在这里分享一下。所以我在里程节点中推送第一个对象:
$model = Customer::findOne($customerId);
if ($model->load(Yii::$app->request->post())) {
$mileage = new mileage(2, 'British Airways', 'Usman', 10000);
$model->mileage = array($mileage);
$model->save();
return $this->redirect(['view', 'id' => (string) $model->_id]);
}
所以要在里程节点中添加另一个对象,我们需要做的是我们需要从数据库中获取客户对象,我们必须检查里程节点中是否已经添加了一个对象然后我必须得到对象并将新创建的里程数组/对象推入其中。修改后的代码如下:
$model = Customer::findOne($customerId);
if ($model->load(Yii::$app->request->post())) {
$mileage = new mileage(2, 'British Airways', 'Kamran', 9000);
if (empty($model->mileage) || count($model->mileage) == 0) {
$model->mileage = array($mileage);
} else {
$allUsedMiles = $model->mileage;
array_push($allUsedMiles, $mileage);
$model->mileage = $allUsedMiles;
}
$model->save();
return $this->redirect(['view', 'id' => (string) $model->_id]);
}
我希望这将有助于未来的人;) 谢谢,