Laravel Eloquent:关系多重有问题&雄辩的“选择”方法无法使用“with”方法

时间:2017-07-28 15:37:51

标签: php laravel orm

我试图制作Eloquent:三种模式的关系。请查看我的代码。

    $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->选择(' id');选择上面关系的表格然后我得到数据,如果我使用它显示空白关系块。

在图像下面,用于最后一个图像整个功能的响应

enter image description here

enter image description here

enter image description here

简而言之,没有选择它可以正常工作,但如果我使用选择然后不工作。

2 个答案:

答案 0 :(得分:2)

Laravel在第一个查询运行后加载关系。为了将相关模型附加到父项,您需要在相关表上选择外键,以便Laravel知道在运行查询后将子项附加到哪个模型。

accountService有效,因为您正在选择该模型上的account_id以将其附加到AccountserviceProvider,因为您选择了id serviceProvider 1}}以及service_provider_id accountService所以在运行所有查询之后,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();

答案 1 :(得分:1)

您需要选择外键以及您要选择的任何其他字段。没有它你就会得到一个空洞的关系。所以它应该类似于$c->select('id', 'account_id');