在对象输出上检索关系字段
Posted
技术标签:
【中文标题】在对象输出上检索关系字段【英文标题】:Retrieve relationship fields on object output 【发布时间】:2021-05-27 16:11:51 【问题描述】:当将客户端对象输出到 JSON 时,我还需要包含区域字段,我该怎么做呢?我尝试过预先加载,但输出不包含字段。
模型
Client
public function Office()
return $this->hasOne('App\Models|offices', 'ref_id', 'OfficeID')->where('DB', '=', $this->RemoteDatabase);
Office
public function region()
return $this->belongsTo('App\Models\Regions', 'regions_id');
获取客户端的代码
$ModelOBJ = Clients::where('ClientCode', 'LIKE', $term)
->orderBy('ClientName', 'ASC');
if ((clone $ModelOBJ)->count() > 0)
$ClientData = $ModelOBJ->with('Office.Region:HRName')->get();
return response()->json(['code' => '200', 'Client' => $ClientData, 'querieis'=> \DB::getQueryLog()]);
这将返回以下内容
code "200"
Client [ …, … ]
querieis [ …, …, … ]
0 Object query: "select count(*) as aggregate from [Clients] where [ClientCode] LIKE ?", time: 56.64, bindings: […]
query "select count(*) as aggregate from [Clients] where [ClientCode] LIKE ?"
bindings [ "test" ]
0 "test"
time 56.64
1 Object query: "select * from [Clients] where [ClientCode] LIKE ? order by [ClientName] asc", time: 59.12, bindings: […]
query "select * from [Clients] where [ClientCode] LIKE ? order by [ClientName] asc"
bindings [ "test" ]
0 "test"
time 59.12
2 Object query: "select * from [Offices] where [Active] = ? and [DB] is null and [Offices].[ref_id] in (?, ?)", time: 2.55, bindings: […]
query "select * from [Offices] where [Active] = ? and [DB] is null and [Offices].[ref_id] in (?, ?)"
bindings [ "Y", "1", "5" ]
time 2.55
【问题讨论】:
【参考方案1】:在预先加载中加载特定字段时,您还应该选择用于映射相关记录的记录标识符。所以在你的情况下(belongsTo)
它的id
Region
的主键
$ModelOBJ->with('Office.Region:id,HRName')->get();
See Eager Loading Specific Columns
使用此功能时,您应该始终在要检索的列列表中包含 id 列和任何相关的外键列。
【讨论】:
以上是关于在对象输出上检索关系字段的主要内容,如果未能解决你的问题,请参考以下文章
jstl标签和el表达式如何输出list中的object对象,object对象是数据库多表查询的结果,不是一个bean的字段