簡體   English   中英

將 pivot 表關聯到 laravel 中的另一個表

[英]relate pivot table to another table in laravel

我與以下結構存在多對多關系:

|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關系生成一個 pivot 表,其中包含所述表的鍵,但我還有第三個foreign key引用另一個表"employees" ,我如何關聯這個表員工和我的桌子? pivot? 嘗試為 pivot 表創建一個 model 並建立關系,除了使用->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');
    }
}

猜想你需要進行以下兩個更改

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);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM