I'm trying to develop an app where one can make his own program with different activities. So far I have 3 tables, the first one is the program table :

// Program table
id - integer
title - string

Then I have a program_activities table

// Program_Activities Table
id - integer
program_id - integer
activity_id - integer
activity_type - string

And then I have all my different activities (Sightseeing, Camping, etc...)

How can I access all activities through the Program model? Something like this

// Program.php

Class Program extends Model
{
    [...]

    public function activities()
    {
        // retrurn all activities
    }
}

So that $session->activities would list me all the activities from that session?

Thank you in advance.

1 Answers

0
Kévan Sadeghi On

Okay, so I "kinda" resolved my problem, but I don't really think it's good practice nor do I think it's optimal. Nontheless, here's my solution. If somebody find a better way, please show me.

// Program.php

    [...]

    /**
     * Get the activities of the program.
     */
    public function activities()
    {
        $program_activities = $this->hasMany('App\ProgramActivity')->get();
        $activities = [];
        foreach ($program_activities as $program_activity){
            $className = $program_activity->activity_type;
            $activity = $className::find($program_activity->activity_id);

            $activities[] = $activity;
        }
        $activities = collect($activities);
        return $activities;
    }

That way, when I do $program->activities(), I do get all the activities of the program.

Even though I think there is a better way to do this, or I think Laravel might cover this with one of it's many relations, I didn't found any. If you have a better answer, then please post it =)