Romentigo
4 months ago
208
1
Laravel

Check if data exists by 2 relationships

Posted 4 months ago by Romentigo

I have 3 models: Department, Lecturer and Subject. Department hasMany lecturers and subjects. Lecturer and subject belongsTo department. I need to get only those departments, that have at least 1 lecturer AND 1 subject. My example is next:

public function withLecturers($id)
    {
        $departments = Department::has('lecturers')->with('institute', 'lecturers')->where('institute_id', '=', $id)
            ->orderBy('name', 'ASC')->get();

        if ($departments->isEmpty())
        {
            return response()->json(['message' => 'На цьому ННІ немає жодної кафедри.'])->setStatusCode(500);
        }
        else
        {
            return response()->json($departments)->setStatusCode(200);
        }
    }

How can I use Department::has for both relations?

Please sign in or create an account to participate in this conversation.