Laravel - 如何根据员工和登录用户获取公司详细信息

Laravel - How to get company detail based on employee and logged user

在我的 Laravel 8 应用程序中,我有以下模型。

公司

protected $fillable = [
    'id',
    'name',
    'website',
    'company_logo',
    'registration_number',
    'date_established',
    'address',
];

员工

protected $fillable = [
    'id',
    'company_id',
    'user_id',
    'first_name',
    'last_name',
    'other_name',
    'gender',
];

public function company()
{
    return $this->belongsTo(Company::class,'company_id','id');
}

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

我开始了这个但是在路上卡住了。我想 select 基于登录用户的公司详细信息。公司table应该是主要table:

public function getMyCompany()
{
    try {
        $userId = Auth::user()->id;
        $employeeId = Employee::where('user_id', $userId)->first();
        $company = Company::...;

        return $this->success('Company successfully Retrieved.', [
            'company' => $company
        ]);
    } catch (\Exception $e) {
        Log::error($e);

        return $this->error($e->getMessage(), $e->getCode());
    }
}

我如何实现这一目标(select 公司的所有详细信息)使用:

$company = Company::...;

制作主模型

我不确定您是希望从用户那里获得多家公司,还是只是一家公司。我不确定的原因是您已经定义了公司与员工之间的 1-1 关系,但看起来您希望 getMyCompany() 到 return 多家公司。

如果只想检索员工工作的一家公司,您可以使用员工的“属于”关系,如下所示:

$company = $employee->company;

由于您已经检索到与经过身份验证的用户相关的员工,并且员工模型具有“公司”关系。

如果您想一次性完成,您可以链接查询:

$company = Employee::where('user_id', Auth::user()->id)
                     ->first()
                     ->company;

为此使用 Eloquent 预加载,因为 Employee 模型与 company

belongsTo 关系
public function getMyCompany()
{
    try {
        $userId = Auth::user()->id;
        $employee = Employee::with('company')->where('user_id',$userId)->first();
        $company = $employee->company
        return $this->success('Company successfully Retrieved.', [
            'company'         => $company
        ]);
    } catch(\Exception $e) {
        Log::error($e);
        return $this->error($e->getMessage(), $e->getCode());
    }
}

请参阅:https://laravel.com/docs/8.x/eloquent-relationships#eager-loading 了解预加载在 Laravel

中的工作原理