【问题标题】:Get Departmenr name from department id using eloquent laravel使用 eloquent laravel 从部门 id 获取部门名称
【发布时间】:2021-07-23 20:17:14
【问题描述】:

我有这个用户表

id | name |      email     | department_id

1    user 1  xyz@gmail.com        2

这是部门表

id |  department_name 

1      Admin 
2      Account

有工资表:

id |  user_id |  basic_pay

1        1          5000

我在工资模型中有这种员工关系

class Salary extends Model
{
   public function employee(){
      return $this->belongsTo('App\User','user_id','id');
   }
}

我还想获取与哪个用户关联的部门名称

  $Data =  Salary::where('id',$id)->with('employee')->first();

但目前我只能借助员工关系获取部门 ID。

非常感谢任何帮助。

【问题讨论】:

  • 您是否尝试过添加员工与部门之间的关系?调用department() 然后在查询中使用with('employee.department')

标签: laravel laravel-5 eloquent


【解决方案1】:

您可以向名为 department 的 User 模型添加另一个关系,如下所示:

public function department()
{
    return $this->belongsTo(Department::class);
}

然后在此处记录用户点符号:https://laravel.com/docs/8.x/eloquent-relationships#nested-eager-loading。看起来像这样

Salary::where('id', $id)->with('employee.department')->first();

此外,您可以使用 find 方法简化此操作,如下所示:

Salary::with('employee.department')->find($id);

由于 find 将返回模型(在本例中为 Salary 模型),因此您需要反转其他方法。

如果您不知道薪水是否存在,您可能需要使用findOrFail 记录在此https://laravel.com/docs/8.x/eloquent#not-found-exceptions

【讨论】:

    【解决方案2】:
    Data =  Salary::where('id',$id)->with('employee.department')->first();
    

    在您的员工模型中添加如下关系

       public function department(){
        return $this->belongsTo('App\Department','department_id');
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-20
      • 2021-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多