You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel多态关联如何仅返回指定列?

解决方案

针对你的需求,这里有几种无需修改User模型hidden属性的实现方式:

1. 查询时指定关联字段

在查询Customer时,通过with()的闭包筛选User的返回字段,必须包含关联所需的外键(model_id和model_type),否则Laravel无法建立关联:

$customers = Customer::with(['user' => function ($query) {
    $query->select('id', 'username', 'model_id', 'model_type');
}])->get();

2. 定义专属的精简关联

在Customer模型中新增一个专门返回精简User数据的关联方法,和原有的user关联区分开:

// Customer模型原有关联
public function user()
{ 
    return $this->morphOne(User::class, 'model');
}

// 新增精简关联
public function minimalUser()
{
    return $this->morphOne(User::class, 'model')
        ->select('id', 'username', 'model_id', 'model_type');
}

使用时直接调用这个新关联:

$customers = Customer::with('minimalUser')->get();

3. 使用API资源统一格式化返回

如果是API场景,推荐用Laravel的API资源标准化返回结构,完全隔离不同接口的字段需求:

首先创建Customer资源:

php artisan make:resource CustomerResource

然后在CustomerResource中定义返回字段:

// app/Http/Resources/CustomerResource.php
public function toArray($request)
{
    return [
        // 其他Customer字段
        'id' => $this->id,
        'name' => $this->name,
        // 只返回User的指定字段
        'user' => [
            'id' => $this->user->id,
            'username' => $this->user->username
        ]
    ];
}

在控制器中返回资源:

return CustomerResource::collection(Customer::with('user')->get());

如果需要复用User的精简返回格式,还可以创建UserMinimalResource,然后在CustomerResource中引用:

// app/Http/Resources/UserMinimalResource.php
public function toArray($request)
{
    return [
        'id' => $this->id,
        'username' => $this->username
    ];
}

// CustomerResource中修改
'user' => new UserMinimalResource($this->user)

内容的提问来源于stack exchange,提问作者RobinBang

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 04:45:44