laraveleloquentrelationship

Is it possible to combine collections in Eloquent relationships in Laravel?


I have a query that can get data on 3 relationships as a result: Relationship1, Relationship2 and Relationship3. But the problem is that in some cases, there may be fewer of these relationships. Tell me, is it possible to combine these relationships in one query and, for example, specify them under a specific alias, for example, RelationshipResult?

I read about the merge() function, but as I understand it, it can only combine existing collections, and is not used in the process of obtaining these collections...

Continuing with the question

UPD:

enter image description here

Debugging data, for example, two relationship with different names, and can the collections of these connections be combined into one?


Solution

  • Oh yeah. I got it. I'll post the answer in case it's useful to someone. I tried to use merge() earlier, but I should have used union().

    In the models we do:

    public function myRelation_1 {
      return $this->myRelation()->where('level', 1);
    }
    
    public function myRelation_2 {
      return $this->myRelation()->where('level', 2);
    }
    
    // Add
    public function all_relation() {
      return $this->myRelation_1()->union($this->myRelation_2());
    }
    
    // When calling in the controller, pass the following to the with() method
    $res = Model::select('id','name', 'price')
    ->with('all_relation')
    ->where('status', '=', 1)
    ->first();
    

    PS: Maybe it will be useful to someone. Thank you all for participating.