Laravel用雄辩的方式查询多个表 [英] Laravel query multiple tables using eloquent

查看:31
本文介绍了Laravel用雄辩的方式查询多个表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这里对新手表示抱歉,但我有3个表的用户,个人资料和朋友.它们都具有user_id字段,我想使用Eloquent而不是 DB :: statement 并在执行表联接时在一条语句中获取所有字段.

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.

我该如何实现?

推荐答案

尝试一下

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

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

这篇关于Laravel用雄辩的方式查询多个表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆