Laravel merge relationships

前端 未结 4 611
深忆病人
深忆病人 2020-11-29 09:21

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         


        
4条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-29 10:07

    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();
    

提交回复
热议问题