eloquent - Laravel 5 Eloquent "with"方法: joining multiple tables and filter columns in joined tables

标签 eloquent laravel-5

我将用户和用户配置文件存储在两个单独的表中,其中“用户”表具有用户名和电子邮件列,“用户配置文件”表具有名称和员工编号列。

用户.php

public function userProfile()
{
    return $this->hasOne('App\Models\Utility\UserProfile', 'user_id', 'id');
}

用户配置文件.php

public function users()
{
    return $this->belongsTo('App\Models\Utility\User', 'user_id', 'id');
}

我正在使用 with 方法来加载用户的个人资料信息。 以下代码加载具有个人资料的用户列表,并可以过滤用户名列和电子邮件列。

用户管理 Controller .php

public function getUserProfile(){
    $users = User::with('UserProfile')
            ->where('username', 'LIKE', '%'.Input::get('q').'%')
            ->orWhere('email', 'LIKE', '%'.Input::get('q').'%')
            ->paginate(5);


    return view('user_profile',compact('users'));
}

但是我无法过滤 UserProfile 表中的 name 和employee_no 字段,因为我无法访问这些字段。 那么 Eloquent 的连接多个表以及过滤连接表中的列的方式是什么呢?

最佳答案

public function getUserProfile(){
$users = User::join('UserProfile', 'users.id', '=', 'UserProfile.user_id')
        ->where('username', 'LIKE', '%'.Input::get('q').'%')
        ->orWhere('email', 'LIKE', '%'.Input::get('q').'%')
        ->orWhere('UserProfile.employee_id', 'LIKE', '%'.Input::get('q').'%')
        ->orWhere('UserProfile.name', 'LIKE', '%'.Input::get('q').'%')
        ->paginate(5);


return view('user_profile',compact('users'));

}

在 Laravel 查询生成器中使用 join 方法解决了问题

关于eloquent - Laravel 5 Eloquent "with"方法: joining multiple tables and filter columns in joined tables,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30010437/

相关文章:

php - Laravel Eloquent 如何加入查询而不是表?

php - 无法访问 Laravel 中的一个特定模型,得到一个空白页面

mysql - 如何在 Laravel 5 中多次加入和使用 withCount

php - 拉维尔 : Eager loading pivot table and sorting on pivot table field

php - Laravel 日期未插入,更新数据库表

mysql - 如何使用 Laravel ORM 在 MySQL 表中插入数组

php - 如何在默认用户模型上设置 Eloquent 关系

php - Response 内容必须是实现 __toString() 的字符串或对象,移动到 psql 后给出的 "boolean"

laravel - 更新 Composer 时出现错误

php - 如何在 leftjoin 中使用多个条件与 laravel5 中的原始查询