Connect PivotTable to another table in Laravel
P粉073857911
P粉073857911 2024-03-27 10:16:01
0
1
413

I have a many-to-many relationship with the following structure:

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

As you can see, I have the typical many-to-many relationship, resulting in a pivot table containing the keys from said table, but I also have a third foreign key Reference another table "employees", how can I associate this employee table with my table? pivot? Tried creating a model for the pivot table and establishing relationships other than using ->using() but so far it hasn't worked for me and I'll leave you with the one I currently Model example.

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

reply all(1)
P粉315680565

I guess you need to make the following two changes

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);
    }
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template