【问题标题】:Laravel, Eloquent Many to Many with Many To Many in Pivot tableLaravel,雄辩的多对多与数据透视表中的多对多
【发布时间】:2017-06-04 14:32:31
【问题描述】:

如何在 Eloquent 模型中表示这一点的最佳方式:

jobs -- ManyToMany -- (提供者 -- ManyToMany-- 服务)

表:

| providers | services  |services_providers | jobs      | jobs_services_providers
--------------------------------------------------------------------------------------
| id        | id        | id                | id        | id                        |
|           |           | providers_id      |           | services_providers_id     |
|           |           | services_id       |           | job_id                    |
|           |           | price             |           | price                     |

谢谢!

【问题讨论】:

    标签: mysql laravel laravel-5 eloquent pivot-table


    【解决方案1】:

    使用here 提供的 Laravel 官方文档,您的模型应该是这样的

    模特工作

    class Jobs extends Model {    
        public function providers(){
            return $this->belongsToMany('App\Providers');
        }    
    }
    

    模型提供者

    class Providers extends Model {
        public function jobs(){
            return $this->belongsToMany('App\Jobs');
        }
        public function services(){
            return $this->belongsToMany('App\Services');
        }
    }
    

    模型服务

    class Services extends Model {    
        public function providers(){
            return $this->belongsToMany('App\Providers');
        }    
    }
    

    如果您使用数据透视表,那么您可以在模型中定义数据透视表

    return $this->belongsToMany('App\Providers', 'services_providers');
    

    如果您想在 Eloquent 中自定义数据透视关系中的字段,请使用类似

    return $this->belongsToMany('App\Providers', 'services_providers', 'service_id', 'provider_id');
    

    对于所有其他帮助,您应该可以使用 LARAVEL OFFICIAL DOCUMENTATION

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 2017-02-12
      • 1970-01-01
      • 2020-03-11
      • 2019-03-25
      • 1970-01-01
      • 2016-11-03
      • 2013-01-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多