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

Laravel读取hasMany关联表返回完整数组而非指定字段值问题排查

问题描述

Laravel框架开发过程中,关联查询第二张关联表数据时返回完整对象数组,而非预期的对应字段值。
现有两张业务表:

  • packages:套餐表
  • resources:存储套餐对应资源的资源表

当前套餐名称、价格字段读取展示正常,但读取关联资源数据时,返回如下完整对象数组:

[{"id":2,"resource":"Vegetarian menu","package_id":2,"created_at":"2022-06-18T19:34:48.000000Z","updated_at":"2022-06-18T19:34:48.000000Z"},{"id":3,"resource":"Standard Menu","package_id":2,"created_at":"2022-06-18T19:35:31.000000Z","updated_at":"2022-06-18T19:35:31.000000Z"}]

预期仅输出对应resource字段的值:Vegetarian menu、Standard Menu。

现有业务代码

Package模型

class Package extends Model { 
    use HasFactory;

    protected $fillable = ['name'];

    public function resources()
    {
        return $this->hasMany(Resource::class);
    } 
}

Package控制器

class PackageController extends Controller {
    public function index(){
        // SELECT * FROM packages
        $packages = Package::with('resources')->get();
        return view('service', compact('packages')); 
    } 
}

Resource模型

class Resource extends Model {
    use HasFactory;

    protected $fillable = ['package_id', 'resource'];

    public function package()
    {
        return $this->belongsTo(Package::class);
    } 
}

前端视图代码

@foreach ($packages as $package)
<div class="tile is-parent"><!-- each child tile needs it's own parent -->
    <article class="tile is-child box has-text-centered">
        <figure class="image is-96x96 is-inline-block">
            <img class="is-rounded" src="https://bulma.io/images/placeholders/96x96.png" alt="">
        </figure>

        <p class="subtitle has-text-centered">{{ $package->name }}</p>
        
        <h4 class="is-size-5 has-text-centered">£{{ number_format($package->cost) }}.00</h4>

        <div class="content">
            <ul>
                <li>{{ $package->resources }}</li>
            </ul>
        </div><!-- content -->

    </article>
</div><!-- parent -->
@endforeach
问题原因

$package->resources是hasMany关联返回的Resource模型集合,包含关联资源的全量字段,直接在模板输出时会将整个集合转义为JSON字符串打印,不符合输出单个资源名称的预期。

解决方案

修改前端视图的资源渲染逻辑,遍历关联的资源集合,单独输出每个资源的resource字段即可:

<div class="content">
    <ul>
        @foreach($package->resources as $res)
        <li>{{ $res->resource }}</li>
        @endforeach
    </ul>
</div>

如果需要在查询阶段就只取回需要的字段,也可以修改控制器的预加载逻辑,指定关联查询字段:

$packages = Package::with('resources:id,package_id,resource')->get();

注意:hasMany关联预加载指定字段时,必须包含关联外键package_id和关联主键id,否则关联数据无法正确匹配。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 09:15:36