user3410847
user3410847

Reputation:

Laravel query multiple tables using eloquent

hi sorry bit of a newbie here but I am have three tables users, profiles, friends. they all have the user_id fields within them and I want fetch all of the fields in one statement using Eloquent and not DB::statement and doing the table joins.

How can I achieve this?

Upvotes: 14

Views: 5097

Answers (2)

user0129e021939232
user0129e021939232

Reputation: 6355

Try this

use the User class and the with method that laravel has to query model relationships

$user = User::with(['profile', 'friend'])->get();

Ensure your models has the correct relationships as follows:

app/models/User.php

public function friend () {
    return $this->hasMany('Friend');
}

public function profile () {
    return $this->hasOne('Profile');
}

app/models/Profile.php

  public function user() {
        return $this->belongsTo('User');

    }

app/models/Friend.php

public function user() {
    return $this->belongsTo('User');
}

Upvotes: 17

Mahdi Abedi
Mahdi Abedi

Reputation: 146

use some thing like this: You should define relations in your models with hasOne, hasMany.

class Review extends Eloquent {
    public function relatedGallery()
    {
        $this->hasOne('Gallery', 'foreign_id', 'local_id');
    }
}

class Gallery extends Eloquent {
    public function relatedReviews()
    {
        $this->hasMany('Review', 'foreign_id', 'local_id');
    }
}

$gallery = Gallery::with('relatedReviews')->find($id);
Will bring the object Gallery with

$gallery->id
gallery->name
...

$gallery->relatedReviews // array containing the related Review Objects

Upvotes: 0

Related Questions