简体   繁体   中英

Laravel: Many To Many relationship with only 2 tables

I am trying to implement a tagging feature into a small piece of software and for simplicity reasons I'd like to actually only use two tables, just like so:

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))

With the models

<?php

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

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

and

<?php

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

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

However, I can't seem to get this working as the belongsToMany function seems to expect three tables and anyway Laravel seems to want a tags table. I know, that my plan of using only two tables is not really elegant as it increases redundancy, but still it would be acceptable for my use case. So is there any quick solution for this?

This is not a belongsToMany relationship but a hasMany . Each item has many tags.

The problem with this approach is that if in the future you want to change the name of a tag or add an extra field such as a description, you will have to do an update of all the database rows with that tag. It's much easier to just have a dedicated table for the tags, like so :

tags
- id (int)
- name (string)

And setup your pivot table like so :

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

This way, you can easily change the name of a tag, add an extra column and things like that, without ever needing to affect more than one entry.

Once you have these three tables (couting the items one you have), your belongsToMany relationships will work, and you don't even have to specify the name of the primary keys/table, as long as you follow the proper naming scheme.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM