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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?