簡體   English   中英

Laravel:只有2個表的多對多關系

[英]Laravel: Many To Many relationship with only 2 tables

我試圖在一個小的軟件中實現標記功能,出於簡單原因,我實際上只想使用兩個表,就像這樣:

items (first table)
- id (int)
- title (string)
- description (string)

item_tag (second "pivot" table)
- item_id (int, foreign key to item.id)
- tag_name (string (!))
(primary_key(item_id, tag_name))

與模型

<?php

class Item extends Eloquent {
    protected $fillable = array('title', 'desription');

    public function tags() {
        return $this->belongsToMany('Tag', 'item_tag', 'item_id', 'tag_name');
    }
}

<?php

class Tag extends Eloquent {
    protected $fillable = array('tag_name');

    public function items() {
        return $this->belongsToMany('Item', 'item_tag', 'item_id', 'tag_name');
    }
}

但是,我似乎無法belongsToMany正常工作,因為belongsToMany函數似乎期望使用三個表,而Laravel似乎想要一個tags表。 我知道,我只使用兩個表的計划並不是很優雅,因為它增加了冗余,但是對於我的用例來說還是可以接受的。 那么對此有什么快速解決方案嗎?

這不是一個belongsToMany關系,而是hasMany 每個項目都有許多標簽。

這種方法的問題在於,如果將來您想更改標簽的名稱或添加額外的字段(例如描述),則必須使用該標簽對所有數據庫行進行更新。 擁有一個專用的標簽表會容易得多,就像這樣:

tags
- id (int)
- name (string)

然后像這樣設置數據透視表:

item_tag
- id (int)
- item_id (int)
- tag_id (int)

這樣,您可以輕松更改標簽的名稱,添加額外的列以及類似內容,而無需影響多個條目。

一旦擁有了這三個表(將您所擁有的項目表述為一個表),只要您遵循正確的命名方案,您的belongsToMany關系就將起作用,您甚至不必指定主鍵/表的名稱。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM