php - Laravel 我可以使用数据透视表作为模型吗

标签 php laravel

我有三个表员工客户服务

我已经为客户和服务创建了数据透视表作为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/

相关文章:

php - 在 UWP 应用中使用 Php 脚本从 MySql 服务器获取数据

php - mysql_fetch_array 仅获取第一个结果,即使使用 while 循环

php - MYSQL:将SELECT结果中的多个结果插入表中

php - 从 Laravel 中的表中选择行

javascript - Jquery 将 div 中的文本拖放到较小的 div 中

laravel - 我在 laravel scout : Your requirements could not be resolved to an installable set of packages 中遇到此错误

database - Laravel 3 Schema 表列整理

javascript - Laravel AJAX - 记住多个选择的过滤器

Laravel - CreateMany 如果不存在

php - 使用 Laravel Eloquent 为具有唯一用户的帖子点赞或收藏