Wednesday, May 9, 2018

Laravel 5.5 – Load Polymorphic Relationship Model Conditonally? - development

Laravel 5.5 – Load Polymorphic Relationship Model Conditonally?

I have two models User,Post, and a polymorphic table that I need to query to get the two models. In the polymorphic table, the type field is either user or post. When querying the table, if the type is user then loading the user fields are returned. However, if the type is post, I need to pull out the post and the post’s owner user as nested in the post. So basically a conditional based on type which should return the user or post.user. I am trying to use eloquent for this so it takes care of it in a single eloquent query, here is some code to show what I am trying to do:

Query (lovable function attempt not working):

$query = LovableLove::with(['lovable' => function ($q) {
                             if($q->type == 'post') {
                                 $q->with('lovable.post.user');
                             }
                           }] 
                           ->take(10) 
                           ->get();

Relations:

class User extends Model {
    public function posts() {
        return $this->hasMany('AppPost');
    }

    public function lovableLoves() {
      return $this->morphMany('AppLovableLove', 'lovable');
    }
}

class Post extends Model {
    public function user() {
        return $this->belongsTo('AppUser');
    }

    public function lovableLoves() {
      return $this->morphMany('AppLovableLove', 'lovable');
    }
}

class LovableLove extends Model {
    public function lovable() {
        return $this->morphTo();
    }

    public function post() {
        return $this->belongsTo('AppPost', 'lovable_id');
    }
}

Any idea how to get the conditional nesting of the post.user to be in the results as well?



from Laravel Questions and Answers https://laravelquestions.com/laravel/laravel-5-5-load-polymorphic-relationship-model-conditonally/
via Lzo Media

No comments:

Post a Comment