Mateusz Kaleta
Mateusz Kaleta

Reputation: 137

Laravel get related data from 3 tables

I have three tables: users, emails,attachments. User table is connected with emails by user_id. Emails table is connected with attachments by email_id.

My question is: How should I make it look eloquent in laravel to get all users their emails and their attachments? (I know how get all user and they emails but I don't know how to add attachments.)

Upvotes: 2

Views: 1533

Answers (1)

The Alpha
The Alpha

Reputation: 146191

Depending on your database relationship,you may declare a relationship method in your Email model, for example:

// One to One (If Email has only one attachment)
public function attachment()
{
    return $this->hasOne(Attachment::class);
}

Otherwise:

// One to Many (If Email contains more than one attachment)
public function attachments()
{
    return $this->hasMany(Attachment::class);
}

To retrieve the related attachment(s) from Email model when reading a user using id, you may try something like this:

$user = User::with('email.attachment')->find(1); // For One-to-One
$user = User::with('email.attachments')->find(1); // For One-to-Many

Hope you've already declared the relationship method in the User model for Email model using the method name email.

Note: make sure, you have used right namespace for models. It may work if you've done everything right and followed the Laravel convention, otherwise do some research. Also check the documentation.

Upvotes: 4

Related Questions