將資料透視表與 Laravel 中的另一個表相關聯
P粉073857911
P粉073857911 2024-03-27 10:16:01
0
1
393

我具有以下結構的多對多關係:

|Table receipts       |
|- id                 |
|- code               |
|- date               |
-----------------------
|Table plans          |
|- id                 |
|- number             |
|- name               |
-----------------------
|Table plan_receipt   |(Pivot)  
|- id                 |
|- receipt_id         |
|- plan_id            |
|- employee_id        |
-----------------------
|Table employees      |
|- id                 |
|- name               |
-----------------------

如您所見,我有典型的many-to-many 關係,產生一個包含所述表的鍵的資料透視表,但我還有第三個foreign key 引用另一個表格"employees",如何我可以將這張員工表與我的表格關聯起來嗎?樞?除了使用->using() 之外,嘗試為資料透視表創建一個模型並建立關係,但到目前為止它對我來說還沒有工作,我給你留下一個我當前模型的例子。

class Receipt extends Model
{
    public function plans()
    {
        return $this->belongsToMany(Plan::class)->using(PlanReceipt::class);
    }
}

class Plan extends Model
{
    public function receipts()
    {
        return $this->belongsToMany(Receipt::class);
    }
}

class PlanReceipt extends Pivot
{
    protected $table = 'plan_receipt';

    public function employee()
    {
        return $this->belongsTo(Employee::class, 'employee_id');
    }
}

class Employee extends Model
{
    public function plan_receipt()
    {
        return $this->hasMany(PlanReceipt::class, 'id');
    }
}

P粉073857911
P粉073857911

全部回覆(1)
P粉315680565

我猜您需要進行以下兩項更改

class Employee extends Model
{
    public function plan_receipt()
    {
        //Specifying foreign key is not required as it is as per Eloquent convention
        return $this->hasMany(PlanReceipt::class);

        //If you want to specify the keys then it should be
        // return $this->hasMany(PlanReceipt::class, 'employee_id', 'id');
    }
}
class PlanReceipt extends Pivot
{
    protected $table = 'plan_receipt';

    //Assuming the id column on plan_receipt table is auto incrementing 
    public $incrementing = true; 

    public function employee()
    {
        //return $this->belongsTo(Employee::class, 'employee_id');

        //Specifying foreign key is not required as it is already as per Laravel Eloquent convention
        return $this->belongsTo(Employee::class);
    }
}
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板