我有3种内容类型,课程,位置和时间表。课程属于多个位置,位置也属于许多课程,但是时间表只能属于一个课程和一个位置。我已经通过数据透视表(course_location)在课程模型和位置上建立了多对多关系。我的问题在于如何用模型中的数据透视表进行连接/引用时间表,或者我做错了方法。
表结构
**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,
],
];
}
我只将belongTo
与时间表模型一起使用,并将hasOne
与位置和课程模型一起使用。
这同时适用于课程和位置。
class Course extends Model
{
public $hasOne = [
'schedule' => ['Author\Plugin\Models\Schedule']
];
}
class Location extends Model
{
public $hasOne = [
'schedule' => ['Author\Plugin\Models\Schedule']
];
}
这是预定的时间
class Schedule extends Model
{
public $belongsTo = [
'course' => ['Author\Plugin\Models\Course'],
'location' => ['Author\Plugin\Models\Location']
];
}
然后您只需要向计划表添加course_id
和location_id
列。然后,您可以通过时间表记录或您想要的方式访问课程记录和位置记录。
实验性-我从未尝试过此方法
在这种情况下,您可以指定多对多关系表中的course_location
在不同的关系中,并且它可能起作用。
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']
];
}