在 Laravel 4 中使用枢轴 table 时如何分配关系?

How to assign relation when working with pivot table in Laravel 4?

详情

我有 3 张桌子:

图表

我不确定我是否正确设置了它们之间的关系。 如果我错了,请纠正我。

这是我做的

CatalogDownload.php

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

ExportFrequency.php

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

问题

谢谢

由于 export_frequenciesCatalogDownload 模型中,您必须反转 ID,因为 belongsToMany 的参数如下:

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)

是什么导致了这个功能:

public function export_frequencies(){ 

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

其他功能正确。

如果您的数据透视表 table 中有一些数据,例如名称为 someCounter 的列,那么您必须在像这样创建数据透视表对象时告诉关系加载该列:

public function export_frequencies(){ 

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

这将加载该列并使其可用,如下所示:

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

如果您需要对字段进行一些特殊处理,或者如果该枢轴本身有自己的关系,您将需要一个单独的枢轴模型,但您可能会考虑使用完整的模型而不是纯枢轴模型.

作为已接受答案的补充说明,只要您遵循特定约定,就可以在不引用数据透视表 table 和相关 ID 的情况下设置多对多关系。

您可以使用对相关 table 的单数引用来命名您的枢轴 table,例如“catalog_download_export_frequency”。 注意单数引用的字母顺序

那么你可以简单地做:

// CatalogDownload Model
public function exportFrequencies()
{
    return $this->belongsToMany('ExportFrequency');
}

// ExportFrequency Model
public function catalogDownloads()
{
    return $this->belongsToMany('CatalogDownload');
}

这将允许您使用查询构建器或 Eloquent 运行 查询,例如:

$catalogDownload->exportFrequencies()->get(); // Get all export frequencies for a specific CatalogDownload.

或者

$this->catalogDownload->with('exportFrequencies')->find($id); // Using eager loading and dependency injection, when CatalogDownload is assigned to $this->catalogDownload

希望对您有所帮助!