dongwen7371 2015-01-16 15:30
浏览 35
已采纳

在Laravel 4中使用数据透视表时如何分配关系?

Details

I have 3 tables :

  • catalog_downloads
  • export_frequencies
  • export_frequencies_catalog_downloads (Pivot Table)

Diagram

enter image description here

I am not sure if I set the relation between them correctly. Please correct me if I am wrong.

Here is what I did

In CatalogDownload.php

public function export_frequencies(){ 
        return $this->belongsToMany('ExportFrequency','export_frequencies_catalog_downloads','export_frequency_id','catalog_download_id');
    }

In ExportFrequency.php

public function catalog_downloads(){ 
        return $this->belongsToMany('CatalogDownload','export_frequencies_catalog_downloads','export_frequency_id','catalog_download_id');
    }

Questions

  • According to my diagram - Did I assign the relationship correctly ? I hope I didn't mix up between hasMany and belongsTo

  • Will I need a class or a model for a Pivot Table ?

Thanks

  • 写回答

2条回答 默认 最新

  • dongyang2229 2015-01-16 16:02
    关注

    Since export_frequencies is in the CatalogDownload model you have to invert the ID's because the parameters of belongsToMany are as follows:

    1. Name of the referenced (target) Model (ExportFrequency)
    2. Name of the Pivot table
    3. Name of the id colum of the referencing (local) Model (CatalogDownload in this case)
    4. Name of the id colum of the referenced (target) Model (ExportFrequency in this case)
    

    what leads to this function:

    public function export_frequencies(){ 
    
            return $this->belongsToMany('ExportFrequency','export_frequencies_catalog_downloads','export_frequency_id','catalog_download_id');
        }
    

    The other function was correct.

    If you had some data in your pivot table, for instance a colum with the name someCounter then you will have to tell the relation to load that column when creating the pivot object like this:

    public function export_frequencies(){ 
    
            return $this->belongsToMany('ExportFrequency','export_frequencies_catalog_downloads','export_frequency_id','catalog_download_id')->withPivot('someCounter');
    }
    

    That will load the column and make it avalible like this:

    $catalogDownload->export_frequencies()->first()->pivot->someCounter;
    

    You will need a separate Pivot Model if you need to do some special handling for the fields or if that pivot itself has a relation of its own but then you might consider using a full blown model instead of a pure Pivot Model.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)