Laravel Eloquent 关系 keyBy()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45987487/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel Eloquent relationship keyBy()
提问by Petyo Tsonev
i want to modify the result set of relationship in the following way
我想通过以下方式修改关系的结果集
I have this array
我有这个数组
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 [?] ]
I want to map classificationand classification_databy column key ( type OR method ) which are loaded relationships. This is the query:
我想通过加载关系的列键(类型 OR 方法)映射分类和分类数据。这是查询:
$case = RCase::with(['user','order','classification','classificationData','teethConfiguration'])->where('id',$id)
->first();
This is what i tried so far
这是我到目前为止尝试过的
$case->classificationData = $case->classificationData->keyBy('type')->toArray();
With the first method they are ordered by type but the old classification_datastays there even if try to
使用第一种方法,它们按类型排序,但旧的分类数据保留在那里,即使尝试
unlink($case->classification_data)这不是大问题......我也可以这样做 classification分类,但数据保持不变。
Is there any method with which i can do keyBy() straight in the loaded relation model ?Thanks in advance
有什么方法可以在加载的关系模型中直接执行 keyBy() 吗?提前致谢
PHP Version: 7.1 Laravel Version: 5.4.38 OS: Ubuntu 16.04 LTS
回答by Arthur Samarcos
You can replace the relation with this code:
您可以使用以下代码替换关系:
$case->setRelation("classification_data",$case->classificationData->keyBy('type'));
To replace the relation you must provide the same relation name or laravel will create another one.
要替换关系,您必须提供相同的关系名称,否则 laravel 将创建另一个关系。
When you do:
当你这样做时:
$case->classificationData = something
You are actually adding a new attribute to the model object.
您实际上是在向模型对象添加一个新属性。