Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

dziewxc's avatar

Querying relations on trashed instances

Our team is using soft deleting functionality and we wonder if there is an option for querying relations on trashed instances. For now we have code:

           $userId = Auth::user()->id;
           $students->onlyTrashed();
           $students->whereHas('teachers',
               function ($query) use($userId) {
               $query->where('teacher_id', '=', $userId);
           });

And it's generates sql query that returns students that are not active, but "whereHas" relation is checked for active students. Is there a way for checking this condition on non-active students? Or do you operate on assumption that deleted instances should not have relations?

This is SQL that is generated:

SELECT
  *
FROM
  `users`
WHERE
  `role` = 'Student' AND `school_id` = '8'
      AND `users`.`deleted_at` IS NOT NULL
      AND (SELECT
          COUNT(*)
      FROM
          `users` AS `self_30381522579b6fdb3936f0c7fcea08ff`
              INNER JOIN
          `students_teachers` ON `self_30381522579b6fdb3936f0c7fcea08ff`.`id` = `students_teachers`.`teacher_id`
      WHERE
          `users`.`deleted_at` IS NULL
              AND `students_teachers`.`student_id` = `users`.`id`
              AND `teacher_id` = '5'
              AND `users`.`deleted_at` IS NULL) >= 1
LIMIT 25 OFFSET 0

Also, why "deleted_at is null" is only added for students and not for teachers in generated sql?

0 likes
0 replies

Please or to participate in this conversation.