我有三个表员工,客户,服务。
我已经为 customer_service (有额外的字段)创建了客户和服务的支点。
现在我想将员工链接到customer_service。所以我尝试将customer_service用作模型' Custserv '并尝试与员工相关联。它没有锻炼。
因为我不希望员工直接链接到客户和服务
我有以下关系工作
/*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();
});
然后我试了......
$staff = User::find(1)->custservs;
return $staff;
它给出了错误
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)
如果我的关系是正确的,如何在Staff和Custserv之间获取和设置值?
答案 0 :(得分:1)
你可能已经弄明白了,但我认为你这样做过于复杂。当使用多对多关系时,Laravel提供pivot
属性。您的关系中已经有withPivot
。
现在您可以像这样访问它:
$staff = User::find(1)->services()->first()->pivot; // or you could loop over services
return $staff;