ThingEngineer / PHP-MySQLi-Database-Class

Wrapper for a PHP MySQL class, which utilizes MySQLi and prepared statements.
Other
3.29k stars 1.35k forks source link

Working with "helper tables" #935

Open geek-at opened 3 years ago

geek-at commented 3 years ago

Hello! Thanks for this awesome project it's exactly what I was looking for.

I'm having troubles with n:n relations in databases.

I have 3 tables:

  1. Users
  2. Channels (one user can have multiple channels)
  3. users_channels

The third one is a "helper" table I use to relate the data in the database (foreign keys, etc)

Now I'm not sure how I can efficiently work with these because relations as explained here won't work since I can only map directly between Users and Channels for example.

At the moment my User class (which extends dbObject) has a custom function "loadChannels()" where I have successfully (but very very ugly) combined the data.

    private $channels;
    function loadChannels()
    {
        $user_channel = dbObject::table("user_channel");
        $user_channel = $user_channel->where('user',Flight::get('user')->id)->join('User', 'user');
        $user_channel = $user_channel->join('Channel', 'channel');
        $this->channels = array();
        foreach ($user_channel->get() as $p) {
            $thischan = new Channel;
            $thischan->byId($p->id);
            $this->channels[] = $thischan;
        }
    }

My question is: Is there an easier or more elegant way to map n:n?