laravel集合合并和组合两个不同的数据集



如果集合中的数字项不相等,我如何合并集合?我尝试了映射、合并等。没有得到我想要的结果。$vitals = $animal->getLatestVitals();

// Get the conditions based on the animal's vitals
if($vitals)
{
$vitalIds = $vitals->pluck('vital_id', 'value')->toArray();
$conditionVitals = DB::table('condition_vital')
->whereIn('vital_id', $vitalIds)->get();
$collections = $conditionVitals->merge($vitals);

dd($collections);
$filtered = $collections->filter(function ($value, $key) {
if($value->value){
return $value;
}
});
IlluminateSupportCollection {#1704 ▼
#items: array:7 [▼
0 => {#1698 ▼
+"condition_id": 51
+"vital_id": 2
+"min": "6"
+"max": "9"
}
1 => {#1753 ▼
+"condition_id": 95
+"vital_id": 3
+"min": "3"
+"max": "4"
}
2 => {#1748 ▼
+"id": "anim_1656735049BzJoGENzpBfip43"
+"name": "weight"
+"value": "80"
+"created_at": "2022-08-14 00:00:00"
+"animal_id": "ani_1656730205DMhSBgby671VEdazd"
+"vital_id": 1
}
3 => {#1747 ▼
+"id": "anim_1656735049oDpMUQ5PJkKdVS8ddd"
+"name": "body_score"
+"value": "8"
+"created_at": "2022-07-14 00:00:00"
+"animal_id": "ani_1656730205DMhSBgby671VEdazd"
+"vital_id": 2
}
4 => {#1744 ▼
+"id": "anim_1656739859JliRP0IawXz987J"
+"name": "dental_score"
+"value": "2"
+"created_at": "2022-09-01 00:00:00"
+"animal_id": "ani_1656730205DMhSBgby671VEdazd"
+"vital_id": 3
}

]
#escapeWhenCastingToString: false
}

我已经合并了集合,现在我需要它们来组合数组,如果重要的ID匹配和最小/最大值。像这样:我不需要任何不包含最小值和最大值的项——但我确实需要将它们合并在一起。

IlluminateSupportCollection {#1704 ▼
#items: array:7 [▼

1 => {#1747 ▼
+"id": "anim_1656735049oDpMUQ5PJkKdVS8ddd"
+"name": "body_score"
+"value": "8"
+"created_at": "2022-07-14 00:00:00"
+"animal_id": "ani_1656730205DMhSBgby671VEdazd"
+"condition_id": 51
+"vital_id": 2
+"min": "6"
+"max": "9"
}
2 => {#1744 ▼
+"id": "anim_1656739859JliRP0IawXz987J"
+"name": "dental_score"
+"value": "2"
+"created_at": "2022-09-01 00:00:00"
+"animal_id": "ani_1656730205DMhSBgby671VEdazd"
+"condition_id": 95
+"vital_id": 3
+"min": "3"
+"max": "4"
}
}

]
#escapeWhenCastingToString: false
}

您不需要首先将它们组合在一起,您可以通过在model中创建一个关系,然后在查询生成器中调用它来实现这一点,假设您有一个条件生命值的模型,您可以这样做:

ConditionVitals.php模型

function vital(){
return $this->hasOne(Vital::class);
}

,然后在查询中使用with()函数调用此关系,如下所示:

ConditionVitals::whereIn('vital_id', $vitalIds)->with('vital')->get();

这会给你一个漂亮而干净的集合,就像这样:

{
"id": "anim_1656735049BzJoGENzpBfip43"
"name": "weight"
"value": "80"
"created_at": "2022-08-14 00:00:00"
"animal_id": "ani_1656730205DMhSBgby671VEdazd"
"vital_id": 1
"vital:{
"condition_id": 51
"vital_id": 1
"min": "6"
"max": "9"
}
}

这种方式只会获取那些需要的记录,而不是获取具有不匹配id的整个表。同理可以创建belongsTo()关系。但是要确保这些id是受限的,以避免任何类型的异常,因为否则关系将无法工作。在这里获得帮助

相关内容

  • 没有找到相关文章