28

Is there a way to merge 2 relationships in laravel?

this is the way it's setup now, but Is there a way I could return both merged?

  public function CompetitionsHome() {
    return $this->HasMany( 'Competition', 'home_team_id' );
  }
  public function CompetitionsGuest() {
    return $this->HasMany( 'Competition', 'guest_team_id' );
  }
  public function Competitions() {
    // return both CompetitionsHome & CompetitionsGuest
  }
Wahyu Kristianto
  • 8,719
  • 6
  • 43
  • 68
Kiwi
  • 2,713
  • 7
  • 44
  • 82

6 Answers6

36

Try out getter method for property which returns merged collections returned from relations.

public function getCompetitionsAttribute($value)
{
    // There two calls return collections
    // as defined in relations.
    $competitionsHome = $this->competitionsHome;
    $competitionsGuest = $this->competitionsGuest;

    // Merge collections and return single collection.
    return $competitionsHome->merge($competitionsGuest);
}

Or you can call additional methods before collection is returned to get different result sets.

public function getCompetitionsAttribute($value)
{
    // There two calls return collections
    // as defined in relations.
    // `latest()` method is shorthand for `orderBy('created_at', 'desc')`
    // method call.
    $competitionsHome = $this->competitionsHome()->latest()->get();
    $competitionsGuest = $this->competitionsGuest()->latest()->get();

    // Merge collections and return single collection.
    return $competitionsHome->merge($competitionsGuest);
}
Andreyco
  • 22,476
  • 5
  • 61
  • 65
  • You can read more about available Collection methods here http://laravel.com/api/class-Illuminate.Support.Collection.html#methods – Andreyco Jun 12 '14 at 12:37
  • 8
    While this works, it should be noted that this doesn't return a relationship instance. Therefore you can't do something like `App\User::find(1)->with('competitions')`, but you can do `App\User::find(1)->with('competitions_guest')` (barring any syntax errors) – daraul Sep 26 '17 at 14:23
  • 2
    @daraul is there a possibility how to merge relations and use them in the querybuilder? – Adam May 16 '18 at 08:47
  • Wouldn't this also require an `protected $appends = ['competitions'];` property to be added to the Model class? – Potherca Aug 04 '21 at 12:57
9

In case you prefer merge() method to combine two collections (relationships), it will override elements with the same index keys so you will loose some of your data gained from one relationship.

You should choose push() method instead, which creates new array keys by pushing one collection to the end of other collection

Here is a sample :

public function getCompetitionsAttribute($value) {
    $competitionsHome = $this->competitionsHome;
    $competitionsGuest = $this->competitionsGuest;

    // PUSH ONE TO OTHER!
    return $competitionsHome->push($competitionsGuest);
}
spetsnaz
  • 1,181
  • 1
  • 14
  • 11
5

I've created a package for merging relationships using views:
https://github.com/staudenmeir/laravel-merged-relations

First, create the merge view in a migration:

use Staudenmeir\LaravelMergedRelations\Facades\Schema;

Schema::createMergeView(
    'competitions',
    [(new YourModel)->CompetitionsHome(), (new YourModel)->CompetitionsGuest()]
);

Then define the relationship:

class YourModel extends Model
{
    use \Staudenmeir\LaravelMergedRelations\Eloquent\HasMergedRelationships;

    public function competitions()
    {
        return $this->mergedRelationWithModel(Competition::class, 'competitions');
    }
}

Use it like any other relationship:

$model->competitions;

$model->competitions()->paginate();

YourModel::with('competitions')->get();
Jonas Staudenmeir
  • 24,815
  • 6
  • 63
  • 109
5

I created a package for Laravel that allows you to create a relation that merges multiple hasMany relations, supports eager loading (->with(...)) and you do not need to create a view.

Package on GitHub: https://github.com/korridor/laravel-has-many-merged

Your question would be solved with something like this:

use Korridor\LaravelHasManyMerged\HasManyMergedRelation;

class Example extends Model
{

  use HasManyMergedRelation;

  // ...
  
  public function Competitions() {
    return $this->hasManyMerged('Competition', ['home_team_id', 'guest_team_id']);
  }

}
korridor
  • 133
  • 2
  • 5
2

In Laravel 8 you can do it like this:


  public function Competitions() {
    $home= $this->CompetitionsHome();
    $guest => $this->CompetitionsGuest();

    $all = $home->union($guest)
                ->orderBy('created_at')
                ->get();
  }

Arsii Rasheed
  • 324
  • 1
  • 5
  • 18
0

If anyone landed here like me due to google: As neither merge() nor push() allow eager loading (and other nice relation features), the discussion didn't end with this thread but was continued here: Laravel Eloquent Inner Join on Self Referencing Table

I proposed a solution here, any further ideas and contributions to this issue welcome.

tomstig
  • 379
  • 4
  • 4