dongzhong2008 2019-03-28 22: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 13: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条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部