首页 > 解决方案 > 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 ]); 
    }

我很感激任何帮助!

标签: eloquentlaravel-5.8eloquent-relationship

解决方案


使用文档,这是应该如何安排的。请注意与您的解决方案的区别

  • 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
); 

推荐阅读