比如数据库的设计是下面这样子:
我想展示的是这个样子:
前端可以处理。
Think PHP的处理方式:
定义属性 :
$this->customize = '任意值';//这里的之没有作用
<?php
namespace app\hs\controller\shop;
use app\daogou\model\Goods;
use app\hs\controller\Common;
use app\hs\traits\Curd;
use think\App;
class Lists extends Common
{
use Curd;
public function __construct(App $app = null)
{
parent::__construct($app);
$this->model = new Goods();
$this->alias = 'good';
$this->join = ['user', 'user.id = good.user_id'];
$this->field = 'good.*,username';
$this->customize = 'status_txt';
// $good = $this->model->find();
// dump($good);
// $good->status_txt = '1112312';
// dump($good);
// dump($good->getData("price"));
// die;
}
}
在model 中定义 getXxxxAttr(){} 查询数据库会调用这个函数。对查出来的数据进行预处理
public function getStatusTxtAttr($v,$data)
{
//状态(-1:下架,1:上架,2:交易中)
$status = [-1=>"下架",1=>"上架",2=>"交易中"];
if(array_key_exists('status',$data)){
return array_key_exists($data['status'],$status) ? $status[$data['status']] : $data['status'];
}
return '';
}
<?php
namespace app\daogou\model;
use app\common\model\TimeModel;
class Goods extends TimeModel
{
protected $table = 'dg_goods';
protected $type = [
'type_params'=>'json',
];
//type_params:
// type = 1 : [['coin_id'=>1,'award'=>"0.80000000"],……]
// type = 2 : ['max_number'=>10,'winner'=>1]
// type = 3 : null
public function user()
{
return $this->hasOne('user','user_id','id')->bind(['username']);
}
public function getStatusTxtAttr($v,$data)
{
//状态(-1:下架,1:上架,2:交易中)
$status = [-1=>"下架",1=>"上架",2=>"交易中"];
if(array_key_exists('status',$data)){
return array_key_exists($data['status'],$status) ? $status[$data['status']] : $data['status'];
}
return '';
}
public function getPriceAttr($v)
{
return delZero($v);
}
}