2016-11-05 195 views
1

这里是我的代码:Laravel 5.3关系

class Company extends Model { 
    public function employees() { 
     return $this->hasMany('Employee'); 
    } 
} 

class Employee extends Model{ 
    protected $table = "user_role_company"; 
    public function user(){ 
     return $this->belongsTo('User'); 
    } 
    public function company(){ 
     return $this->belongsTo('Company'); 
    } 
} 

class User extends Authenticatable { 
    public function employee(){ 
     return $this->hasMany('Employee'); 
    } 
} 

如果我运行:

$recordsTotal = User::with(['employee' => function ($query) use ($company_id) { 
    $query->where('company_id', $company_id); 
}])->count(); 

它返回所有的用户数不仅empolyee计数。

我在做什么错?

感谢

回答

0

首先,你有一个“COMPANY_ID”,并在员工模型/ DB一个“user_ID的”列?

不管怎么说,你可以试试这个查询,而不是。

$recordsTotal = User::whereHas('employee', function ($q) use ($company_id) { 
    $q->where('company_id', $company_id); 
})->count(); 
+1

您的查询工作!谢谢!! – user3844579

0

当创建关系需要引用整个命名空间或类似用户::类的类

+0

命名空间被引用 – user3844579

0

当使用关系中,你可以在关系声明莫代尔::类给出主键和地方两个表的键引用正确的值,所以例如你可以有:

class Company extends Model { 
    public function employees() { 
     return $this->hasMany(Employee::class, 'company_id'); 
    } 
} 

这将引用的Employee表中的company_id列或你所设置的员工模态中曾经表。

您也可以通过foreign_key,local_key的关系,像这样:

class Company extends Model { 
    public function employees() { 
    return $this->hasMany(Employee::class, 'foreign_key', 'local_key'); 
    } 
} 

一个类似的例子是:

class Company extends Model { 
    public function employees() { 
    return $this->hasMany(Employee::class, 'company_id', 'company_id'); 
    } 
} 

根据您的数据库结构,你应该能够只通过模态::类的关系,但它是很难给出一个完美的工作示例不知道你的确切数据库结构,以及如何你有你的钥匙/标识设置,意为例子就是你的名为id或COMPANY_ID主键。根据这个结构,你可以给这个镜头。

class Company extends Model { 
public function employees() { 
    return $this->hasMany(Employee::class); 
} 

}

还记得在阵列上返回集合时,要么循环或简单地使用$公司 - >员工() - > get()方法的另一种选择是使用 - >第()而不是get()使用数组中的第一条记录。

希望这会有所帮助,我决不是一个专家,还在学习laravel我自己,如果你有这种关系的任何进一步的问题或不能得到的代码工作,我会尽量帮助我在哪里可以。

也值得看一看这里:Laravel Docs (Eloquent: Relationships)