1 "user_id" => 1 "name" => "Test Case-6ren">
gpt4 book ai didi

php - Laravel Eloquent 关系 keyBy()

转载 作者:可可西里 更新时间:2023-10-31 23:27:34 27 4
gpt4 key购买 nike

我想通过以下方式修改关系的结果集

我有这个数组

    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 classification and classification_data by column key ( type OR method ) which are loaded relationships. This is the query:

 $case = RCase::with(['user','order','classification','classificationData','teethConfiguration'])->where('id',$id)
->first();

这是我目前尝试过的

$case->classificationData =  $case->classificationData->keyBy('type')->toArray();

使用第一种方法,它们按类型排序,但旧的 classification_data 会保留在那里,即使尝试

 unlink($case->classification_data) 
这不是什么大问题...我也可以使用 分类来做到这一点,但数据保持不变。

有什么方法可以直接在加载的关系模型中执行 keyBy() 吗?提前致谢

PHP Version: 7.1Laravel Version: 5.4.38OS: Ubuntu 16.04 LTS

最佳答案

您可以用这段代码替换关系:

$case->setRelation("classification_data",$case->classificationData->keyBy('type'));

要替换关系,您必须提供相同的关系名称,否则 laravel 将创建另一个关系。

当你这样做时:

$case->classificationData = something

您实际上是在向模型对象添加一个新属性。

关于php - Laravel Eloquent 关系 keyBy(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45987487/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com