Laravel query multiple tables using eloquent

你说的曾经没有我的故事 提交于 2021-02-08 12:20:33

问题


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?


回答1:


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');
}



回答2:


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


来源:https://stackoverflow.com/questions/31036781/laravel-query-multiple-tables-using-eloquent

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!