2017-07-28 102 views
1

我嘗試做出雄辯:關係爲三個模型。請看看我的代碼。Laravel雄辯:關係多重有問題和雄辯「選擇」方法不使用「與」方法

$account = Account::select(['id', 'is_sign_contract', 'restaurant_name', 'state', 'phone_no', 'email', 'one_time_pick_up', 'sign_contract_date', 'created_at', 'oil_on_hand', 'binsize']) 
      ->with(['completedservice' => function($c) { 
       //$c->select('id'); 
       }]) 
      ->with(['accountService' => function($q) { 
        $q->with(['serviceProvider' => function($qs) { 
         $qs->select('id', 'company_name'); 
        }])->select('account_id', 'service_provider_id', 'service_id'); 
       }]) 
        ->whereRaw($where) 
        ->orderBy('id', 'ASC')->offset(54)->limit(1)->get(); 

如果我刪除// $ c-> select('id');選擇上面的關係表,然後我得到數據,如果我使用它顯示空白關係塊。

下面的圖片中最後一個圖像整體功能有

enter image description here


enter image description here


enter image description here

總之應答,而不選擇它工作正常,但如果我我正在使用se然後選擇不工作。

+0

是吧'addSelect'如PIC或'// $ C->選擇( '身份證');'爲代碼?並完成服務模式有一個ID字段? – Maraboc

回答

2

Laravel在第一次查詢運行後加載關係。爲了將相關模型附加到父項,您需要在相關表中選擇外鍵,以便Laravel知道在查詢運行後將哪個模型附加到子項。

accountService作品,因爲ytou是在該模型中選擇account_id將其附加到AccountserviceProvider作品,因爲你是在accountService選擇上serviceProviderid以及service_provider_id打完所有查詢都運行Laravel知道哪個模型得到重視地方。

由於您未在子模型上選擇account_id,因此您的查詢不起作用。

下面的工作:

$account = Account::select(['id', 'is_sign_contract', 'restaurant_name', 'state', 'phone_no', 'email', 'one_time_pick_up', 'sign_contract_date', 'created_at', 'oil_on_hand', 'binsize']) 
    ->with(['completedservice' => function($c) { 
     $c->select('id', 'account_id'); 
    }]) 
    ->with(['accountService' => function($q) { 
     $q->with(['serviceProvider' => function($qs) { 
      $qs->select('id', 'company_name'); 
     }]) 
     ->select('account_id', 'service_provider_id', 'service_id'); 
    }]) 
    ->whereRaw($where) 
    ->orderBy('id', 'ASC')->offset(54)->limit(1)->get(); 
+0

謝謝@Eric Tucker幫助我。我對這個問題感到沮喪。非常感謝你幫助我。那個時候我不知道發生了什麼事。我不是想明智地思考它。再次感謝您寶貴的回覆。 –

+0

別擔心,這就是爲什麼。我只知道這個問題的答案,因爲我過去花了幾個小時來調試它;-) –

1

您需要選擇外鍵以及您希望選擇的其他字段。沒有它,你會得到一個空的關係。所以它應該類似於$c->select('id', 'account_id');

+0

感謝您抽出時間回答我的問題。我會感激。但我認爲@eric已經提到了上述答案。和他一樣用英文書寫......所以我明白他說的是什麼。 –