简体   繁体   English

当数据库多对多时返回一对一关系实例

[英]Return a one to one relationship instance when database is many to many

I have a many to many relationship in the database that looks like User -> user_companies -> company. 我在数据库中有许多关系,看起来像User-> user_companies-> company。

My issue is that in terms of our business logic this should be a one to one relationship however correcting this would take a lot of work. 我的问题是,就我们的业务逻辑而言,这应该是一对一的关系,但是要纠正这一点将需要大量工作。 In the pivot table there is only ever one entry of a User. 在数据透视表中,用户永远只有一个条目。

Currently on the user model I am doing this but it returns a model and not a relationship instance. 当前在用户模型上,我正在执行此操作,但是它返回一个模型而不是一个关系实例。

// returns relationship instance
public function companies()
{
    return $this->belongsToMany('App/Company', 'user_companies');
}

// returns model
public function company()
{
    return $this->companies()->first();
}

Is it possible for me to mimic the behaviour of a one to one relationship whilst the database is set up as many to many? 在数据库设置多对多的情况下,我是否可以模仿一对一关系的行为?

UPDATE: 更新:

Laravel has now added a HasOneThrough relationship out of the box. Laravel现在开箱即用地添加了一个HasOneThrough关系。 https://laravel.com/docs/5.8/eloquent-relationships#has-one-through https://laravel.com/docs/5.8/eloquent-relationships#has-one-through

With this, it's possible but you'd really have to dig into the core and build your own custom solution (Relationship Query Builder). 有了这个,这是有可能的,但您实际上必须深入研究核心并构建自己的自定义解决方案(关系查询生成器)。

The first thing that comes to mind is a hasOneThrough relationship method. 首先想到的是hasOneThrough关系方法。 Unfortunately, this does not exist out of the box. 不幸的是,这并不存在。 My recommendation is to find a reliable package to accomplish this. 我的建议是找到一个可靠的软件包来完成此任务。

In fact, I was able to find this package: https://github.com/riesjart/relaquent 实际上,我能够找到此包: https : //github.com/riesjart/relaquent

Otherwise, unless your DB Schema is a complete mess, adding a company_id to your users table and then writing the sql migration script would not be complicated in the least bit. 否则,除非您的数据库架构是一团糟,否则,至少要在您的users表中添加company_id然后编写sql迁移脚本就不会很复杂。 Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM