Laravel 5在两列之间有很多关系 [英] Laravel 5 hasMany relationship on two columns

查看:87
本文介绍了Laravel 5在两列之间有很多关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我的表格有两列, user_id related_user_id



我希望我的关系匹配任何列。



在我的模型中,我有

  public function userRelations()
{
return $ this-> hasMany('App\UserRelation');
}

哪些运行查询: select * from user_relations where user_relations.user_id in('17','18')



我需要运行的查询是:

  select * from user_relations where user_relations.user_id = 17 OR user_relations.related_user_id = 17 

编辑:



我正在使用热心加载,我认为这会影响它将必须工作。

  $ cause = Cause :: with('donations.user.userRelations') - > where ('active','=',1) - > first(); 


解决方案

我不认为可以做到什么你在问



我认为你应该将它们视为单独的关系,然后在模型上创建一个新的方法来检索两者的集合。

  public function userRelations(){
return $ this-> hasMany('App\UserRelation');
}

public function relatedUserRelations(){
return $ this-> hasMany('App\UserRelation','related_user_id');
}

public function allUserRelations(){
return $ this-> userRelations-> merge($ this-> relatedUserRelations);
}

这样,您仍然可以在模型上获得热切的加载和关系缓存的好处。

  $ cause =原因:: with('donations.user.userRelations',
'donations.user.relatedUserRelations ')
- > where('active',1) - > first();

$ userRelations = $ cause-> donations [0] - > user-> allUserRelations();


Is it possible to have a hasMany relationship on two columns?

My table has two columns, user_id and related_user_id.

I want my relation to match either of the columns.

In my model I have

public function userRelations()
{
    return $this->hasMany('App\UserRelation');
}

Which runs the query: select * from user_relations where user_relations.user_id in ('17', '18').

The query I need to run is:

select * from user_relations where user_relations.user_id = 17 OR user_relations.related_user_id = 17 

EDIT:

I'm using eager loading and I think this will affect how it will have to work.

$cause = Cause::with('donations.user.userRelations')->where('active', '=', 1)->first();

解决方案

I don't think it's possible to do exactly what you are asking.

I think you should treat them as separate relationships and then create a new method on the model to retrieve a collection of both.

public function userRelations() {
    return $this->hasMany('App\UserRelation');
}

public function relatedUserRelations() {
    return $this->hasMany('App\UserRelation', 'related_user_id');
}

public function allUserRelations() {
    return $this->userRelations->merge($this->relatedUserRelations);
}

This way you still get the benefit of eager loading and relationship caching on the model.

$cause = Cause::with('donations.user.userRelations', 
        'donations.user.relatedUserRelations')
    ->where('active', 1)->first();

$userRelations = $cause->donations[0]->user->allUserRelations();

这篇关于Laravel 5在两列之间有很多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆