Files
xk-api-yii/member/models/forms/AddressForm.php

126 lines
3.3 KiB
PHP

<?php
namespace member\models\forms;
use common\core\BaseModel;
use common\models\oldDb\Address;
use common\validators\MobileValidator;
use yii\db\Exception;
class AddressForm extends BaseModel
{
public $id;
public $name;
public $mobile;
public $province;
public $city;
public $area;
public $region;
public $detail_address;
public function rules()
{
return [
[['name','region','mobile','detail_address'],'required'],
[['province','city','area'],'string'],
['mobile',MobileValidator::class],
];
}
public function save()
{
if (!$this->validate()){
throw new Exception($this->getErrorMsg());
}
$address=new Address();
$address->name=$this->name;
$address->user_id=\Yii::$app->user->identity->getId();
$address->mobile=$this->mobile;
$address->province=$this->province;
$address->city=$this->city;
$address->area=$this->area;
$address->region=$this->region;
$address->detail_address=$this->detail_address;
$address->save();
}
public function edit($post)
{
if (!$this->validate()){
throw new Exception($this->getErrorMsg());
}
$address=Address::find()->where([
'id'=>$post['id'],
'user_id'=>\Yii::$app->user->identity->getId(),
'is_delete'=>0,
])->one();
if (!$address)throw new Exception('暂无该收货地址');
if($this->province && $this->province != $address->province){
$address->province = $this->province;
$address->city=$this->city;
$address->area=$this->area;
}
$address->name = $this->name;
$address->mobile = $this->mobile;
$address->region = $this->region;
$address->detail_address = $this->detail_address;
$address->save();
}
public function UpdateDefault($post)
{
$address=Address::find()->where([
'id'=>$post['id'],
'user_id'=>\Yii::$app->user->identity->getId(),
'is_delete'=>0,
])->one();
if (!$address)throw new Exception('暂无该收货地址');
$t=\Yii::$app->db->beginTransaction();
try {
Address::updateAll([
'is_default'=>0,
],[
'user_id'=>\Yii::$app->user->identity->getId(),
'is_delete'=>0,
]);
\Yii::$app->db->createCommand()->update('yii_address',[
'is_default'=>1,
],[
'id'=>$post['id'],
'is_delete'=>0,
])->execute();
$t->commit();
}
catch (\Exception $e){
$t->rollBack();
throw new $e;
}
}
public function del($post)
{
$address=Address::find()->where([
'id'=>$post['id'],
'user_id'=>\Yii::$app->user->identity->getId(),
'is_delete'=>0,
])->one();
if (!$address)throw new Exception('暂无该收货地址');
Address::updateAll([
'is_delete'=>1,
],[
'id'=>$post['id'],
'user_id'=>\Yii::$app->user->identity->getId(),
]);
}
}