We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Multiple Groups/Multiple relations

Hi

I'm trying to figure out how to do the following in the best way:

  1. I have some objects(hostnames) which are created in the database

  2. I have some other objects(groups) which are created in the database

I want the hostnames to be members of one or more groups... How do I do this in my model?

edited Oct '16

You will have to create a third table which holds the relation between the other two. Something like:

hostnames_groups_relation example structure:

id hostname_id group_id
1 2 3
2 2 4
3 2 5

And here you can see how to create the relations between the models.

Hmm... I see..

Could you give a short example on how to add a robot to a part (not in the initializer), or howto add a hostname to a group??

So far I have:

Hosts: <?php

  use Phalcon\Mvc\Model;

  class Hosts extends Model
  {
      public $id;

      public $name;

      public $ip;

      public $status;

      public $proxyid;

      public $port;

      public function initialize()
      {
          $this->hasMany(
              "id",
              "HostsGroups",
              "hostid"
          );
      }
  }

Groups: <?php

  use Phalcon\Mvc\Model;

  class Groups extends Model
  {
      public $id;

      public $name;

      public function initialize()
      {
          $this->hasMany(
              "id",
              "HostsGroups",
              "groupid"
          );
      }

  }

HostsGroups: <?php

  use Phalcon\Mvc\Model;

  class HostsGroups extends Model
  {
      public $id;

      public $hostid;

      public $groupid;

      public function initialize()
      {
            // Do I need anything here???
      }
  }
edited Oct '16

Keep in mind using hasMany will return instance of HostsGroups, not Hosts or Groups. If you want to return Hosts or Groups you need to use hasManyToMany relation. Yes you need in HostsGroups belgonsTo

Hmmm.. so I need a hasManyToMany..

What should be in the "belongsTo"?



145.0k
Accepted
answer

Check docs :)

@Wojciech i guess that's thje answer to almost every question on the forum :)))))