Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to access drop-down relationships in Laravel


Models :

  • USER

    • boards() : HasMany
  • BOARD

    • lists() : HasMany
  • LIST

    MEDevel.com: Open-source for Healthcare and Education

    Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

    Visit Medevel

    • tasks() : HasMany
  • TASK


Tables :

Board :

  • id
  • user_id

List :

  • id
  • board_id

Task :

  • id
  • list_id

How do I want to search for a task with an ID, but without creating a relationship in USER?
I can create a relationship in USER called tasks(), but I do not want to do this in this way. I want, for example:

$user = User::find(10);
$task = $user->boards()->lists()->tasks()->find($id);

Note that the tasks and lists table do not have a user_id field, only the board table

I TRY : $task = $user->boards()->lists()->tasks()->find($id);

>Solution :

Go the other way, start with what you want to get.

$userId = 10;
$tast = Task::query()
    ->whereHas('list', function($list) use ($userId) {
        $list->whereHas('board', function($board) use ($userId) {
            $board->where('user_id', $userId);
        });
    })
    ->find($id);

You, of course, need the reverse relations of what you shared in your question.

  • Task -> list
  • list -> board

I would also suggest using findOrFail($id) instead of find($id) so it return a 404 in case of incorrect id.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading