我想以下列方式修改关系的结果集
我有这个数组
array:11 [▼ "id" => 1 "user_id" => 1 "name" => "Test Case" "created_at" => "2017-08-25 17:12:26" "updated_at" => "2017-08-29 11:59:46" "hashid" => "5LOkAdWNDqgVomK" "user" => array:8 [▶] "order" => array:8 [▶] "classification" => array:2 [▼ 0 => array:9 [▼ "id" => 1 "case_id" => 1 "method" => "facial_map_manual" "strong" => 2.0 "dynamic" => 30.0 "delicate" => 50.0 "calm" => 18.0 "created_at" => "2017-08-31 11:00:00" "updated_at" => "2017-08-31 11:00:00" ] 1 => array:9 [▼ "id" => 2 "case_id" => 1 "method" => "interview" "strong" => 20.0 "dynamic" => 25.0 "delicate" => 30.0 "calm" => 25.0 "created_at" => "2017-08-31 11:00:00" "updated_at" => "2017-08-31 11:00:00" ] ] "classification_data" => array:3 [▼ 0 => array:6 [▼ "id" => 1 "case_id" => 1 "type" => "facial_points" "data" => null "created_at" => "2017-08-31 11:00:00" "updated_at" => "2017-08-31 11:00:00" ] 1 => array:6 [▼ "id" => 2 "case_id" => 1 "type" => "interview" "data" => array:4 [▶] "created_at" => "2017-08-31 12:00:00" "updated_at" => "2017-08-31 11:00:00" ] 2 => array:6 [▶] ] "teeth_configuration" => array:6 [▶] ]
我想按列加载关系的列键(类型OR方法)映射分类和 classification_data 。 这是查询:
$case = RCase::with(['user','order','classification','classificationData','teethConfiguration'])->where('id',$id)
->first();
这是我到目前为止所尝试的
$case->classificationData = $case->classificationData->keyBy('type')->toArray();
使用第一种方法,它们按类型排序,但即使尝试
unlink($case->classification_data),旧的 classification_data 也会保留在那里 这不是大问题......我也可以用分类来做到这一点,但数据保持不变。
我是否有任何方法可以在加载的关系模型中直接执行keyBy()?提前致谢
PHP Version: 7.1 Laravel Version: 5.4.38 OS: Ubuntu 16.04 LTS
答案 0 :(得分:1)
您可以使用此代码替换关系:
$case->setRelation("classification_data",$case->classificationData->keyBy('type'));
要替换关系,您必须提供相同的关系名称,否则laravel将创建另一个关系。
当你这样做时:
$case->classificationData = something
您实际上是在模型对象中添加新属性。