Laravel hasOne 通过方法使用 Laravel 9

Laravel hasOne through method using Laravel 9

我正在努力实现的目标。我处理 4 个表:

  1. 分支机构(id(PK),branch_name
  2. 员工 (id(PK), staff_name)
  3. branch_heads(staff_id(FK -员工),branch_id(FK -分支))

规则

  1. 员工所属分部
  2. 分行有很多员工
  3. 每个分支机构由一名员工管理

下面是我的分支模型代码

<?php

namespace App\Models\CompanyStructure;

use App\Models\StaffManagement\Staff;
use Illuminate\Database\Eloquent\Model;
use App\Models\CompanyStructure\BranchHead;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class Branch extends Model
{
    use HasFactory;
    protected $fillable = [
        'branch_name',
    ];

    public function staff()
    {
        return $this->hasMany(Staff::class);
    }

    public function branchhead()
    {
        return $this->hasOne(BranchHead::class);
    }
}

下面是我的员工模型代码

<?php

namespace App\Models\StaffManagement;

use App\Models\CompanyStructure\Branch;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class Staff extends Model
{
    use HasFactory;
    protected $table = 'staff';
    protected $fillable = [
        'staff_name',
    ];

    public function branch()
    {
        return $this->belongsTo(Branch::class);
    }

}

下面是我的 BranchHead 模型代码

<?php

namespace App\Models\CompanyStructure;

use App\Models\StaffManagement\Staff;
use App\Models\CompanyStructure\Branch;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class BranchHead extends Model
{
    use HasFactory;

    protected $fillable = [
        'staff_id',
        'branch_id',
    ];

    public function staff()
    {
        return $this->hasOne(Staff::class);
    }

    public function branch()
    {
        return $this->hasOne(Branch::class);
    }

}

修补程序的结果:

Branch::find(1)->branchhead -- gives me the results of the staff_id that manages a particular branch_id. But can't go beyond that level to get which staff_name that manages which branch.

我正在使用 Laravel 9 和 PHP 8.1

如何获得 staff_names?

staff和branch之间是一对多的关系,有一个特殊的staff实体,可以是branch head。

  • 分支机构 (id(PK), branch_name)
  • staff (id(PK), branch_id(FK -branch), staff_name, is_head_branch)
class Branch extends Model
{
    use HasFactory;
    protected $fillable = [
        'branch_name',
    ];

    public function staff()
    {
        return $this->hasMany(Staff::class);
    }

    public function branchhead()
    {
        return $this->hasOne(staff::class)->where('is_head_branch',1);
    }
}

在评论中添加您对此结构的任何问题。我会在回复中编辑。

要获取分支机构的所有员工,请使用

$branch->staff

会包括总行工作人员(可以在flag上查看$staffMember->is_head_branch == 1

要获得所有 BranchHeads 及其关联的分支机构或其他方式,请这样做

$headBranchs = Staff::where('is_head_branch', 1)->with('branch')->get();
//or
$branchs = Branch::with('branchhead')->get();