cxhxy/app/common/model/food/Address.php
test_service d3170b4d1c 1
2023-12-01 15:43:29 +08:00

1 line
2.7 KiB
PHP

<?php
namespace app\common\model\food;
/**
* 用户地址模型
*/
class Address extends BaseModel
{
// 定义表名
protected $name = 'food_address';
// 定义主键
protected $pk = 'address_id';
// 追加字段
protected $append = [];
/**
* 关联用户表
*/
public function user()
{
return $this->hasOne('app\\common\\model\\food\\User','user_id');
}
/**
* 显示性别
*/
public function getGenderAttr($value)
{
$status = [0 => '未知', 1 => '先生', 2 => '女士'];
return ['text' => $status[$value], 'value' => $value];
}
/**
* 获取列表
*/
public function getList($search = '')
{
$search = trim($search);
$model = $this->with(['user'])->order('address_id','desc');
// 筛选条件
$filter = [];
if(!empty($search)){
//是否是数字
if(is_numeric($search)){
//是否是手机号
if(is_phone($search)){
$filter['phone'] = $search;
}else{
$filter['user_id'] = $search;
}
}else{
//不是数字
$model->where('name','like',"%{$search}%");
}
}
// 执行查询
return $model->where($filter)->paginate(['list_rows'=>15,'query' => request()->param()]);
}
/**
* 新增收货地址
*/
public function add(array $data, $user)
{
if(!is_phone($data['phone'])){
$this->error = '手机号格式不对';
return false;
}
// 添加收货地址
$data['user_id'] = $user['user_id'];
$data['applet_id'] = self::$applet_id;
$this->save($data);
// 设为默认收货地址
!$user['address_id'] && $user->save(['address_id' => $this->address_id]);
return true;
}
/**
* 编辑地址
*/
public function edit(array $data)
{
if(!is_phone($data['phone'])){
$this->error = '手机号格式不对';
return false;
}
return $this->save($data) !== 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();
}
}