L
L
lev892021-09-28 21:34:03
Laravel
lev89, 2021-09-28 21:34:03

How to get related data through an intermediary?

I need to get all users with their requests and comments (see screenshot). How to register the connection in this case?
Comment Model

class Comment extends Model
{
    use HasFactory;
    public function subcategory(){
        return $this->hasMany(Comment::class, 'parent_id');
    }
}

Ticket model
class Ticket extends Model
{
    use HasFactory;
    public function user()
    {
        return $this->belongsTo(User::class);
    }
    public function department()
    {
        return $this->belongsTo(Department::class);
    }
}

Model User
class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;
    public function ticket()
    {
        return $this->hasMany(Ticket::class);
    }
}

61535f39f23d3925488896.png

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
jazzus, 2021-09-29
@jazzus

If you get all user comments - add user_id to comments and hasMany to User.
If tickets with User::with('tickets.comments') and hasmany comments in ticket

M
markinigor, 2021-10-05
@markinigor

https://github.com/staudenmeir/eloquent-has-many-deep

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question