<?php
namespace app\api\model;
use app\common\model\Region;
use app\common\model\UserAddress as UserAddressModel;
class UserAddress extends UserAddressModel
{
protected $hidden = [
'wxapp_id',
'create_time',
'update_time'
];
public function getList($user_id)
{
return self::all(compact('user_id'));
}
public function add($user, $data)
{
$region = explode(',', $data['region']);
$province_id = Region::getIdByName($region[0], 1);
$city_id = Region::getIdByName($region[1], 2, $province_id);
$region_id = Region::getIdByName($region[2], 3, $city_id);
$this->startTrans();
try {
$this->allowField(true)->save([
'name' => $data['name'],
'phone' => $data['phone'],
'province_id' => $province_id,
'city_id' => $city_id,
'region_id' => $region_id,
'detail' => $data['detail'],
'district' => ($region_id === 0 && !empty($region[2])) ? $region[2] : '',
'user_id' => $user['user_id'],
'wxapp_id' => self::$wxapp_id
]);
!$user['address_id'] && $user->save(['address_id' => $this['address_id']]);
$this->commit();
return true;
} catch (\Exception $e) {
$this->error = $e->getMessage();
$this->rollback();
return false;
}
}
public function edit($data)
{
$region = explode(',', $data['region']);
$province_id = Region::getIdByName($region[0], 1);
$city_id = Region::getIdByName($region[1], 2, $province_id);
$region_id = Region::getIdByName($region[2], 3, $city_id);
return $this->allowField(true)->save([
'name' => $data['name'],
'phone' => $data['phone'],
'province_id' => $province_id,
'city_id' => $city_id,
'region_id' => $region_id,
'detail' => $data['detail'],
'district' => ($region_id === 0 && !empty($region[2])) ? $region[2] : '',
]) !== false;
}
public function setDefault($user)
{
return $user->save(['address_id' => $this['address_id']]);
}
public function remove($user)
{
$user['address_id'] == $this['address_id'] && $user->save(['address_id' => 0]);
return $this->delete();
}
public static function detail($user_id, $address_id)
{
return self::get(compact('user_id', 'address_id'));
}
}