2017-08-31 171 views
0

我想要修改的結果集關係以下列方式Laravel鋒關係keyBy()

我有這樣的陣列

 

    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 [▶] 
    ] 

我想通過柱映射分類classification_data鍵(OR型方法),它們是加載關係。 這是查詢:

$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.1 
Laravel Version: 5.4.38 
OS: Ubuntu 16.04 LTS 

回答

0

您可以使用此代碼替換的關係:

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

要更換你必須提供相同的關係名稱或laravel將創造一個又一個的關係。

當你這樣做:

$case->classificationData = something 

你實際上是添加新的屬性模型對象。