Question

I am having trouble figuring out how to handle a model with 'dynamic' related models.

There is a model named Group

When creating a group you can do a GroupGame or GroupGamer. This is specified by a group_type in the Group model. So type 1 would relate to GroupGame and 2 would be GroupGamer.

  1. Am I supposed to do a polymorphic relationship here? And inverse the parent to GroupGame and GroupGamer which share a Group table? Or have Group the parent and it either has a related GroupGame or GroupGamer model.

I have other models like News, Media, etc. which I was planning to relate to Group model by using it's id.

Gist: https://gist.github.com/intradox/55cebe406a0e5c5c69cb

Just not sure how to go about this the right way. Hope this makes sense.

Was it helpful?

Solution

regarding the first part of your question polymorphic relations are the way to go. You create Game and Gamer model and they will both need to be "groupable" type of which will be determined by the "groupable_type" field. In the above case you use 3 tables - for Gamer, Game and the poly Group table.

//example table structure
    CREATE TABLE `group` (
      `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
      `title` varchar(255) NOT NULL,
      `description` varchar(255) NOT NULL,
      `groupable_id` int(11) unsigned NOT NULL,
      `groupable_type` varchar(255) NOT NULL,
      `created_at` datetime NOT NULL,
      `updated_at` datetime NOT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

//app/models/Group.php
class Group extends Eloquent {

    protected $table = 'group';

    public function groupable()
    {
        return $this->morphTo();
    }

}

//app/model/Gamer.php
class Gamer extends Eloquent
{
    ...

    public function group()
    {
        return $this->morphMany('Group', 'groupable');
    }

    ...
}

//app/model/Game.php
class Game extends Eloquent
{
    ...

    public function group()
    {
        return $this->morphMany('Group', 'groupable');
    }

    ...
}

As for the other models, that would be related to groups it's the same case - you can work the magic and also make them "groupable" which will enable you to just store all the group details in one table.

//app/model/News.php
class News extends Eloquent
{
    ...

    public function group()
    {
        return $this->morphMany('Group', 'groupable');
    }

    ...
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top