0

I only want the relations to be loaded if they exist. Normally you use wouldhas().

This is a basic has(): Story::with('comments.user')->has('comments')->find($id); in this case i only want the relation data if the comments relation has the data.

What i am trying to do is get data from 2 different relations: Story::with('comments.user', 'tasks.comments.user')->find($id);

i only want the 'comments.user' if comments relation has any data and i only want the 'tasks.comments.user' if the tasks relation has data. Both are independent and don't rely on eachother. So if my comments relation has data but my task relation doesn't i still want to load the comments relation data and vice versa.

Does anyone know the query for this ?

My story model:

public function comments()
{
    return $this->morphMany('App\Tenant\Comment', 'commentable');
}

public function tasks()
{
    return $this->hasMany('App\Tenant\Task');
}

My comments model:

public function commentable()
{
    return $this->morphTo();
}

public function user()
{
    return $this->belongsTo('App\Tenant\User');
}

My task model:

public function story()
{
    return $this->belongsTo('App\Tenant\Story');
}

public function comments()
{
    return $this->morphMany('App\Tenant\Comment', 'commentable');
}
Neavehni
  • 337
  • 1
  • 2
  • 14
  • I'm not sure I understand what you're asking. – Joundill May 13 '20 at 08:43
  • @Joundill The second query i've shown doesn't work. I want to use has() on both of my relations without effecting each other. If i use it like this it will check if both has() requirements are met to show the relations and if one of them isn't it won't show the other even if it's true. – Neavehni May 13 '20 at 08:46
  • https://stackoverflow.com/questions/30231862/laravel-eloquent-has-with-wherehas-what-do-they-mean try to look on this – Kelvin May 13 '20 at 09:08

1 Answers1

1

The second argument in your has() should be moved to another has().

Story::with('comments.user', 'tasks.comments.user')->has('comments')->has('tasks.comments')->find($id);

Or to check for one of the two:

Story::with('comments.user', 'tasks.comments.user')->has('comments')->orHas('tasks.comments')->find($id);

Joundill
  • 6,828
  • 12
  • 36
  • 50
  • But this way both ```has()``` apply to each relation which i don't want. I want the ```has('comments')``` to only apply to the relation ```'comments.user'``` and the ```has('tasks.comments')``` to apply to ```'tasks.comments.user'```. – Neavehni May 13 '20 at 08:57
  • The `has()` applies to your original query, i.e. it's checking whether the story has a comment, and that it has a task that has a comment. Perhaps you're looking for a more complex query built with `whereHas()`? – Joundill May 13 '20 at 09:03
  • @Neavehni I'm still not sure if I understand your question, but try the second piece of code in my answer. – Joundill May 13 '20 at 09:05