dongzhong2008 2019-03-29 06:06
浏览 50
已采纳

m:m上的1:1变体Laravel 5.5中的雄辩关系:示例是否有效?

I am trying to specify a 1:1 relationship, via orgperson(), despite the m:m nature of an existing relationship, orgs(), so that I can eager load 1 default organization.

I have the following objects, each with a table:

  • person model - important note, defaultOrgID exists on person
  • organization record
  • pivot connecting both (orgperson) with additional fields

Is my "jerry-rigging," as shown in the orgperson() function, valid?

If not, is there anything close that would be?

In the Person model, the relevant relationships are as follows:

    // many-to-many relationship from person to orgs via org-person table
    public function orgs()
    {
        return $this->belongsToMany(Org::class, 'org-person', 'personID', 'orgID');
    }

    // "pivot table" with additional fields
    public function orgperson()
    {
        return $this->belongsTo(OrgPerson::class, 'personID', 'personID')
            ->where([
                ['orgID', $this->defaultOrgID],
                ['personID', $this->personID]
            ]);
    }
  • 写回答

2条回答 默认 最新

  • duanmu8911 2019-05-01 21:49
    关注

    Turns out that this was as simple as I had hoped.

    My intermediate table (org-person) had been defined as a Model. I toyed with having its class extend Pivot instead of Model but, in the end, I stuck with Model.

    The code that works (relationship on my Person model):

    public function orgperson()
    {
        return $this->hasOne(OrgPerson::class, 'personID', 'personID')
            ->where('orgID', $this->defaultOrgID);
    }
    

    This gets me the desired result of being able to have this relation return a single entry from what could be multiple records in the pivot table based on the value in defaultOrgID.

    My problem was using "belongsTo" instead of "hasOne."

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥15 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)