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

Laravel Eloquent关联:如何用whereIn多ID作为外键查询数据

Eloquent关联匹配ID数组获取数据及嵌套数组取值方案

一、实现关联匹配一组ID获取数据

你当前的关联写法有误,hasMany的第二个参数是子模型的外键字段名,第三个是当前模型的关联字段名,不能直接传入ID数组。正确实现分两种场景:

场景1:从当前模型的关联关系中筛选指定ID的子模型

先定义正常的hasMany关联:

public function subModels() {
    // 假设SubModel的外键是parent_id,关联当前模型的id字段
    return $this->hasMany(SubModel::class, 'parent_id', 'id');
}

查询时通过whereIn筛选指定ID的子模型:

// 获取当前模型下,ID在[1,2]中的子模型数据
$targetSubModels = $yourModelInstance->subModels()->whereIn('id', [1,2])->get();

场景2:当前模型存储了子模型ID数组(如JSON字段),关联对应子模型

如果当前模型有字段(如sub_model_ids)存储了子模型的ID数组(比如[1,2]),可直接查询子模型:

// 直接从SubModel中匹配ID数组
$targetSubModels = SubModel::whereIn('id', $yourModelInstance->sub_model_ids)->get();

也可以封装到关联方法中:

public function subModels() {
    return SubModel::whereIn('id', $this->sub_model_ids);
}
// 使用时直接调用
$targetSubModels = $yourModelInstance->subModels->get();

二、从嵌套数组中获取对应数据

如果获取到的子模型数据是嵌套数组(或Eloquent集合转数组后),可通过以下方式取值:

1. 使用Eloquent集合方法(推荐)

如果返回的是Eloquent集合,直接用集合的查询方法定位数据:

// 假设$targetSubModels是Eloquent集合
// 获取ID为1的子模型的嵌套字段(如details下的info)
$targetItem = $targetSubModels->find(1);
$nestedValue = $targetItem->details['info'];

// 若details是JSON字段,需在SubModel中设置$casts自动转数组:
// protected $casts = ['details' => 'array'];

2. 处理纯嵌套数组

如果是纯PHP嵌套数组,用collect转换为集合后操作,或直接循环:

$nestedArray = $targetSubModels->toArray(); // 假设已转为数组

// 方式1:用collect处理
$targetValue = collect($nestedArray)
    ->where('id', 1)
    ->pluck('details.info')
    ->first();

// 方式2:直接循环遍历
$targetValue = null;
foreach ($nestedArray as $item) {
    if ($item['id'] === 1) {
        $targetValue = $item['details']['info'];
        break;
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 02:34:59