Laravel 5.1雄辩的查询语法

时间:2015-12-19 21:08:42

标签: php mysql sql eloquent laravel-5.1

我有以下模型关系。如果用户以员工身份登录,我希望他们能够获得公司的员工列表以及他们分配的角色:

class User {

   // A user can be of an employee user type
   public function employee()
   {
       return $this->hasOne('App\Employee');
   }

   // 
   public function roles()
   {
      return $this->belongsToMany('App\Role');
   }

 }

 class Employee {

    // employee profile belong to a user
    public function user()
    {
       return $this->belongsTo('App\User');
    }

    // employee belongs to a company
    public function company()
    {
       return $this->belongsTo('App\Company');
    }
 }


 class Company {

    public function employees()
    {
        return $this->hasMany('App\Employee'); 
    }
 }

但以下查询无效。我收到错误Column not found: 1054 Unknown column companies.id in WHERE clause

    $employee = Auth::user()->employee;

    $companyEmployees = Company::with(['employees.user.roles' => function ($query) use ($employee) {
        $query->where('companies.id', '=', $employee->company_id)
              ->orderBy('users.created_at', 'desc');
     }])->get();     

用户和员工表具有一对一的关系 所有员工的基本角色类型均为employee,此外他们还可能拥有其他角色,例如managersupervisor等。

如何编写一个查询,为我的公司提供所有员工及其角色?

我试图在公司模型中添加一个hasManyThrough关系,但这也不起作用?

public function users()
{
    return $this->hasManyThrough('App\User', 'App\Employee');
}

3 个答案:

答案 0 :(得分:1)

我认为你很想获得当前用户的同事列表并急切加载用户和角色?

$employee = Auth::user()->employee;
$companyEmployees = Company::with(['employees.user.roles')->find($employee->company_id); 

或者也许:

$companyEmployees = Company::find($employee->company_id)->employees()->with('user.roles')->get();
$sorted = $companyEmployees->sortBy(function($employee){ return $employee->user->created_at; }); 

这可能是一条更直接的路线。您的员工ID是否在用户表中,反之亦然?雄辩的关系很容易倒退。

答案 1 :(得分:0)

Users::select('table_users.id')->with('roles')->join('table_employes', function($join) use ($employee) {

    $join->on('table_employes.user_id','=','table_users.id')->where('table_employes.company_id', '=', $employee->company_id);

})->orderBy('tables_users.created_at')->get();

答案 2 :(得分:-1)

<强> 1。在migrtaion中为数据库表列创建关系:

用户角色

$table->foreign('user_id')->references('id')->on('users');

用户

$table->increments('id');

<强> 2。为每个数据库表创建一个模型以定义关系

User.php(模特)

    public function userRoles()
    {
        return $this->hasOne('App\UserRoles', 'user_id', 'id');

    }

Userroles.php(模特)

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

第3。让控制器处理建议使用REST api的数据库调用

控制器

    use App\User;
    use App\UserRoles;

 class UserController extends Controller
{

    public function index()
        {
            return User::with('userRoles')->orderBy('users.created_at', 'desc')->paginate(50);
        }
}