Laravel 5 hasMany two-column relationship

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

My table has two columns, user_id and related_user_id .

I want my relationship to match any of the columns.

In my model I have

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

Why the request is executed: select * from user_relations where user_relations.user_id in ('17', '18') .

I need to execute the following query:

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

EDIT:

I am using active loading, and I think this will affect how it works.

 $cause = Cause::with('donations.user.userRelations')->where('active', '=', 1)->first(); 
+9
source share
2 answers

I don’t think that you can do exactly what you ask.

I think you should treat them as separate relationships, and then create a new method for the model to extract 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); } 

That way, you still get the benefit of load caching and model relationships.

 $cause = Cause::with('donations.user.userRelations', 'donations.user.relatedUserRelations') ->where('active', 1)->first(); $userRelations = $cause->donations[0]->user->allUserRelations(); 
+19
source

Compoships added support for multi-column relationships in Laravel 5 Eloquent.

This allows you to define relationships using the following syntax:

 public function b() { return $this->hasMany('B', ['key1', 'key2'], ['key1', 'key2']); } 

where both columns must match.

+4
source

Source: https://habr.com/ru/post/985532/


All Articles