我有这3张桌子。我想获得创建客户端的员工姓名
我试过这个
class LeadsModel extends Eloquent
public function researcher_name()
{
$user = $this->belongsTo('users','id','user_id');
return $user->getResults()->belongsTo('employees','id','employee_id');
}
但它返回错误:
"message":"SQLSTATE[42S22]: Column not found: 1054 Unknown column 'employees.employee_id' in 'where clause' (SQL: select * from `employees` where `employees`.`employee_id` in (4))"}}
当我切换id和employee_id时,它不会为用户和员工返回任何关系。
基本上,我需要让客户拥有创建它的员工姓名。
答案 0 :(得分:1)
假设关系:
Client belongsTo User
User belongsTo Employee
简单地称之为:
$client->user->employee;
根据您的架构,以下是为了获得与Employee
相关的Client
所需的关系(通过User
):
// Client model
public function user()
{
return $this->belongsTo('User');
}
// User model
public function employee()
{
return $this->belongsTo('Employee');
}
然后简单地称之为:
$client = Client::find($someId);
$client->user; // single user related to the client
$client->user->employee; // single employee related to the user
您可能想要先检查给定的关系是否存在:
// just an example, don't write it this way ;)
if ($client->user) { // user is not null
if ($client->user->employee) { // employee is not null as well
$client->user->employee->name; // name = field on the employees table
}
}
答案 1 :(得分:0)
您需要Has Many Through关系。
在员工的模型中添加名为clients
的关系:
public function clients()
{
return $this->hasManyThrough('App\Client', 'App\User');
}
然后你可以像下面这样使用它:
Employee::first()->clients()->get();