Sambungkan Jadual Pangsi ke jadual lain dalam Laravel
P粉073857911
P粉073857911 2024-03-27 10:16:01
0
1
382

Saya mempunyai hubungan banyak-ke-banyak dengan struktur berikut:

|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               |
-----------------------

Seperti yang anda boleh lihat, saya mempunyai ciri khas many-to-many 关系,生成一个包含所述表的键的数据透视表,但我还有第三个 foreign key 引用另一个表 "employees",如何我可以将这张员工表与我的表关联起来吗?枢?除了使用 ->using()di luar cubaan mencipta model untuk jadual pangsi dan mewujudkan perhubungan, tetapi setakat ini ia tidak berkesan untuk saya, saya akan meninggalkan anda dengan contoh model semasa saya.

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

membalas semua(1)
P粉315680565

Saya rasa anda perlu membuat dua perubahan berikut

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);
    }
}
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan