Laravel关联查询时如何为响应添加额外对象?
在Laravel查询结果中添加额外对象的方法
针对你的需求,有两种常用实现方式,结合现有代码给出具体操作:
方法一:直接给查询结果赋值(临时添加)
在获取到模型实例后,直接为其添加Contest属性,返回响应时该属性会被自动包含:
$list = new self; $list = $list->where('uuid', $uuid); $list = $list->where('user_id', $user->id)->orWhere('to_user_id', $user->id); $list = $list->with(['touser' => function($q1) { $q1->select('id', 'name', 'email', 'user_image', 'is_active', 'is_profile_completed', 'is_verified'); }]); $list->with(['user' => function($q1) { $q1->select('id', 'name', 'email', 'user_image', 'is_active', 'is_profile_completed', 'is_verified'); }]); $list = $list->first(); // 添加额外的Contest对象 if ($list) { $list->Contest = [ 'name' => null, 'type' => 0 ]; } // 后续返回响应即可,比如 return response()->json($list);
方法二:通过模型访问器全局添加(永久生效)
如果这个Contest属性需要在该模型的所有查询结果中都出现,可以在模型类中配置访问器:
1. 在对应模型类中添加代码
class YourModel extends Model { // 其他模型原有代码... // 指定要自动追加的属性 protected $appends = ['Contest']; // 定义Contest属性的访问器 public function getContestAttribute() { return [ 'name' => null, 'type' => 0 ]; } }
2. 原查询代码无需修改
配置完成后,无论执行该模型的任何查询,返回的实例都会自动带上Contest属性,无需每次手动赋值。
内容的提问来源于stack exchange,提问作者tacec48943
相关产品推荐
相关产品推荐

