14

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?

2 Answers 2

17

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');
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.