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条)

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改