我将用户和用户配置文件存储在两个单独的表中,其中“用户”表具有用户名和电子邮件列,“用户配置文件”表具有名称和员工编号列。
用户.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/