2017-07-28 106 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已经提到了上述答案。和他一样用英文书写......所以我明白他说的是什么。 –