我试图制作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');选择上面关系的表格然后我得到数据,如果我使用它显示空白关系块。
在图像下面,用于最后一个图像整个功能的响应
简而言之,没有选择它可以正常工作,但如果我使用选择然后不工作。
答案 0 :(得分:2)
Laravel在第一个查询运行后加载关系。为了将相关模型附加到父项,您需要在相关表上选择外键,以便Laravel知道在运行查询后将子项附加到哪个模型。
accountService
有效,因为您正在选择该模型上的account_id
以将其附加到Account
和serviceProvider
,因为您选择了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');