Dev Abel
Dev Abel

Reputation: 133

Laravel can I use pivot table as a model

I have three tables staff, customer, service.

I have created pivot for customer and service as customer_service(has extra fields).

Now I want to link the staff to customer_service. So i tried to use customer_service as a model 'Custserv' and tried to relate with staff. It didnt workout.

Because I don't want staff linking directly to customer and service

I had this following relationship working

/*Model - Service*/
public function customer(){
    return $this->belongsToMany('customer')->withPivot(
        'start_date',
        'stop_date',
        'rem_date',
        'due_date',
        'status'
        );
}

/*Model - customer*/
public function services(){
    return $this->belongsToMany('Service')->withPivot(
        'start_date',
        'stop_date',
        'rem_date',
        'due_date',
        'status'
        );
}

////These following relations didnt workout
/*Model - custserv*/ //uses the pivot table customer_service//
public function staff(){
    return $this->belongsToMany('Staff');
}

/*Model - Staff*/
public function custservs(){
    return $this->belongsToMany('Custserv');
}

/*schema for pivot table 'staff' and 'Custserv' */
Schema::create('customer_service_user', function(Blueprint $table)
    {
        $table->increments('id');
        $table->integer('customer_service_id')->unsigned()->index();
        $table->foreign('customer_service_id')->references('id')->on('customer_service')->onDelete('cascade');
        $table->integer('staff_id')->unsigned()->index();
        $table->foreign('staff_id')->references('id')->on('staff')->onDelete('cascade');
        $table->timestamps();
    });

Then I tried ...

$staff = User::find(1)->custservs;
return $staff;

It gave error

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'auditCrm_db.custserv_user' doesn't exist (SQL: select `customer_service`.*, `custserv_user`.`user_id` as `pivot_user_id`, `custserv_user`.`custserv_id` as `pivot_custserv_id` from `customer_service` inner join `custserv_user` on `customer_service`.`id` = `custserv_user`.`custserv_id` where `custserv_user`.`user_id` = 1) 

If my relationshiop is correct how to get and set values between Staff and Custserv?

Upvotes: 2

Views: 13641

Answers (1)

lukasgeiter
lukasgeiter

Reputation: 153020

You may have figured it out, but I think you are doing it overly complicated. When using a many-to-many relationship Laravel provides the pivot property. You already have withPivot in your relationship.

Now you can access it like that:

$staff = User::find(1)->services()->first()->pivot; // or you could loop over services
return $staff;

Upvotes: 4

Related Questions