eloquent - Laravel 5.8 hasOneThrough 关系问题
问题描述
有人可以纠正这个吗!我已经断断续续地敲了两天!我从来没有成功地建立 hasOneThrough 关系,但我决定再试一次。现在我得到的错误是“调用未定义的方法 App\Models\OppModels\opp_main::hasOneThrough()”。我相信我的问题在于本地键与外键,但如果我真的知道这些问题,那么我可以解决它。我确实意识到我可以将 org_id 硬编码到我的 opp_main 表中,但出于未来的考虑,我真的很想完成这项工作。我的桌子设计是:
---------
opp_main
---------
id
---------
---------
opp_org
---------
id
opp_id
org_id
---------
---------
org_main
---------
id
---------
我的关系看起来是这样的(评论来自文档,试图在我的脑海中组织它):
public function org()
{
return $this->hasOneThrough(
'App\Models\OrgModels\org_main', // Final model
'App\Models\OppModels\opp_org', // Intermediate model
'opp_id', // Foreign key on intermediate model
'id', // Foreign key on the final model
'id', // local key
'org_id' // local key of the intermediate model
);
}
这就是我的称呼(我已经尝试过 $item->org; 和 $item->org(); ):
public function getAllOpportunities()
{
$opps = opp_main::orderBy('status', 'asc')->get();
$opps->map(function ($item) {
$item['org'] = $item->org;
return $item;
});
return response()->json([ 'success' => true, 'data' => $opps ]);
}
我很感激任何帮助!
解决方案
使用文档,这是应该如何安排的。请注意与您的解决方案的区别
- Org_main 对 opp_org 有一个 FK,在 hasOneThrough() 中需要它来将所需模型链接到中间模型
org_main
ID
opp_org_id
opp_org id opp_id
org_id
opp_main
ID
return $this->hasOneThrough(
'org_main', // final model
'opp_org', // intermediate or linking model
'opp_id', //fk on opp_org linking to opp_main
'opp_org_id', // fk on org_main linking ot opp_org table,
'id', //local key on opp_main
'id', //local key on opp_org / intermediate model
);
推荐阅读
- tkinter - 我没有使用 tkinter 在 python idle 上打印输出
- r - Logistic 回归模型未出现在 Plot() 上 - 似乎是 lines() 问题
- java - 不要在使用 Spring Cloud Stream 的反应函数中将消息标记为已确认
- vulkan - Vulkan 验证层 VkCmdWaitEvents srcStageMask 错误含义
- mongodb - Mongodb:连接到现有文档
- java - Big Query Java 客户端的代理设置
- bash - 自动将其他有用信息添加到 git 存档文件名
- angular - Nginx:带有 Web 组件的 Angular 应用程序 - 脚本类型 =“模块”错误
- java - Javamail 正文与附件一起时不出现
- java - RecyclerView 单击侦听器未在行单击时触发