我有三个表员工、客户、服务。
我已经为客户和服务创建了数据透视表作为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 之间的值?
最佳答案
你可能已经明白了,但我认为你做得太复杂了。当使用多对多关系时,Laravel 提供 pivot
属性(property)。您的关系中已存在 withPivot
。
现在您可以像这样访问它:
$staff = User::find(1)->services()->first()->pivot; // or you could loop over services
return $staff;
关于php - Laravel 我可以使用数据透视表作为模型吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26922812/