一、方法一:Thinkphp5模型输出只visible,hidden,append,appendRelationAttr
<?php
// application/index/controller/index3.php
namespace app\index\controller;
use app\index\model\Region;
use think\Controller;
use app\index\model\ShippingArea;
use app\index\model\User as mUser;
class index3 extends Controller
{
public function test2(){
$user = mUser::get(1);
// 模型输出
// var_dump($user->toArray());
// echo $user->toJson();
// 隐藏属性
// 隐藏一些属性输出
// echo $user->hidden(['reg_time'])->toJson();
// 指定属性
// 指定一些属性输出
// echo $user->visible(['reg_time'])->toJson();
// 追加属性
// 如果读取器定义了一些非数据库字段的读取,例如:
// var_dump($user->append(['user_status'])->toArray());
/// echo($user->append(['user_status'])->toJson());
// 输出Json
echo $user;
}
}
方法二:关联预载入限制关联表的字段的显示:$v->hidden(['roominfo'=>['builtup_area','carpet_area', 'addons']]);
public function index()
{
//设置过滤方法
$this->request->filter(['strip_tags', 'trim']);
if ($this->request->isAjax()) {
//如果发送的来源是Selectpage,则转发到Selectpage
if ($this->request->request('keyField')) {
return $this->selectpage();
}
list($where, $sort, $order, $offset, $limit) = $this->buildparams();
$list = $this->model
->with(['roominfo'])
->where($where)
->order($sort, $order)
->paginate($limit);
foreach ($list as $k=>$v) {
//$v->avatar = $v->avatar ? cdnurl($v->avatar, true) : letter_avatar($v->nickname);
$v->hidden(['roominfo'=>['builtup_area','carpet_area', 'addons']]);
//$row->visible(['builtup_area','carpet_area','deposit']);
}
$result = array("total" => $list->total(), "rows" => $list->items());
return json($result);
}
return $this->view->fetch();
}
方法三:关联预载入,指定属性查询(只显示某字段,类似于visible)
$list = User::field('id,name')->with(['profile'=>function($query){$query->field('email,phone');}])->select([1,2,3]);
foreach($list as $user){
// 获取用户关联的profile模型数据
dump($user->profile);
}
二、关联预载入查询
1、以下两种情况中,关联预载入两个表时,想要约束查询字段。thinkphp5.0中的方法失效,需要用以下方法withField,没有时间去研究具体的原因。
->with(['user'=>function($query){$query->field('id,username,nickname,prevtime,logintime,jointime');},'communityowner']) //无效
->with(['user'=>function($query){$query->withField('username,nickname,prevtime,logintime,jointime');},'communityowner']) //有效
2、注意"相对关联"中的$this->belongsTo的方法,
A、在一对一、一对多的查询中是定义在被关联的表中,如user->profile 就是定义在profile的model中。
B、而关联预载入(有::with())则是定义在user的model中
3、其它思考:我感觉像复杂的关联,预载入,应该让开发者自己去实现,复杂的业务只会把框架整懵,暴露出框架的很多问题,而自己也深陷其中不知道怎么回事,感觉再牛逼的程序也经不住超复杂的业务。不要随便指定字段 会破坏关联数据的查询的
4、setEagerlyType(1)及setEagerlyType(0) 是关联预载入的方法。setEagerlyType(0)表示JOIN
方式(一次查询)。setEagerlyType(1)表示JOIN方式(一次查询)
三、副表搜索
{field: 'communityowner.realname', title: __('业主姓名'),formatter: function(value, row, index){
return row['communityowner']['realname'];
}},
四、多对多关联查询的多态查询(也可以进行条件筛选)
public function enterprice()
{
return $this->belongsToMany('EnterPriceModel','RelationTable','aid','bid')
->where('pivot.type',3);
}
五、es6检测数据类型
Object.prototype.toString.call(this.form.list.zh_name)
typeof(this.form.list.zh_name)
Array.isArray(this.form.list.zh_name)