Ad

How Should I Config Laravel / OctoberCMS Model For Table That Needs To Reference Pivot Table?

I have 3 content type, course, location and schedule. Course belongs many locations, location also belongs to many courses, but schedule can only belong to one course and one location.
I already set up many to many relationship on Course model and Location through a pivot table (course_location). My problem comes with how to do wire up / reference the schedule with the pivot table in model, or I am doing it the wrong way.

Tables structure

**course Table**
id
name

**location Table**
id
name

**course_location Pivot Table**
id
course_id
location_id

**schedule Table**
id
course_id
location_id
time
class Course extends Model
{
    public $belongsToMany = [
        'locations' => [
            Location::class,
            'table'      => 'course_location',
            'key'        => 'course_id',
            'otherKey'   => 'location_id',
            'timestamps' => true,
        ],
    ];
}

class Location extends Model
{
    public $belongsToMany = [
        'courses' => [
            Course::class,
            'table'      => 'course_location',
            'key'        => 'location_id',
            'otherKey'   => 'course_id',
            'timestamps' => true,
        ],
    ];
}
Ad

Answer

I would just use a belongTo with the schedule model and a hasOne with both location and course model.

This is for both the course and location.

class Course extends Model
{
    public $hasOne = [
        'schedule' => ['Author\Plugin\Models\Schedule']
    ];
}

class Location extends Model
{
    public $hasOne = [
        'schedule' => ['Author\Plugin\Models\Schedule']
    ];
}

This is for the schedule

class Schedule extends Model
{
    public $belongsTo = [
        'course' => ['Author\Plugin\Models\Course'],
        'location' => ['Author\Plugin\Models\Location']
    ];
}

And then you would have to add only course_id and location_id columns to the schedule table. You can then access the course record and location record through a schedule record or however way you want.

Experimental - I have never tried this

You might be able to specify the many to many relationship table in this case the course_location in the different relationships and it might work.

class Course extends Model
{
    public $hasOne = [
        'schedule' => ['Author\Plugin\Models\Schedule', 'table' => 'course_location']
    ];
}

class Location extends Model
{
    public $hasOne = [
        'schedule' => ['Author\Plugin\Models\Schedule', 'table' => 'course_location']
    ];
}

class Schedule extends Model
{
    public $belongsTo = [
        'course' => ['Author\Plugin\Models\Course', 'table' => 'course_location'],
        'location' => ['Author\Plugin\Models\Location', 'table' => 'course_location']
    ];
}
Ad
source: stackoverflow.com
Ad