Laravel使用eloquent查询多个表

13 laravel eloquent

嗨抱歉这里的新手,但我有三个表用户,个人资料,朋友.它们都有user_id字段,我希望使用Eloquent获取一个语句中的所有字段,而不是DB::statement执行表连接.

我怎样才能做到这一点?

001*_*221 15

试试这个

使用laravel查询模型关系的User类和with方法

$user = User::with(['profile', 'friend'])->get();
Run Code Online (Sandbox Code Playgroud)

确保您的模型具有如下正确的关系:

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');
}
Run Code Online (Sandbox Code Playgroud)