Search code examples
phpmysqlrelational-databaselaravellaravel-3

Querying 3 tables mysql Laravel


I have multiple tables.

  • Contests
  • Entries
  • Users

User can submit entries to a contest, a user can submit multiple entries to a contest.

I need to know the emails of the users that submitted an entry to a particular contest. The emails are in the user table.

Getting all the entries from a contest isn't that hard, I accomplish this by:

$entries = Contest::find(1)->entries()->first();

Now I have all the entries belonging to the contest with an id of 1(for example use). Now, how do I get all the user emails from my users table in an efficient manner?

So three tables that are linked, I start with the contest id then get all the entries from that contest and then need to get all the user emails wich I haven't been able to get yet.

Hopefully this makes sense. If not, ask away!


Solution

  • $getUser = Contest::find(1)->users()->get();
    $getEmails = $getUser->email;
    
    foreach($getEmails as $getEmail)
        echo $getEmail;
    

    You'll get all the user emails corresponding to the contest id 1. But first you must do the database relation in model to get this to work.