我有以下问题:
我有三张桌子:
contacts (people)
departments
contact_types (e.g. IT-Contact)
所有这些都是多对多类型;一个人可以负责0-n部门作为0-n Contact_types(即使是与多个类型相同的部门)。等等。
此外,我必须在整个项目中拥有历史记录,因此每个表都存储“valid_start”和“valid_end”时间戳。
因此我现在有了这个关系表:
contact_contact_type_department
id
contact_id
contact_type_id
department_id
valid_start
valid_end
我最终做的是为中间表创建一个模型:
class DepartmentResponsible extends Model {
protected $table = 'contact_contact_type_department';
protected $fillable = [...];
protected $dates = [
'valid_start',
'valid_end',
];
protected static function boot(){
parent::boot();
static::addGlobalScope(new ValidScope());
}
public function contact() {
return $this->belongsTo('cap\Contact');
}
public function department() {
return $this->belongsTo('cap\Department');
}
public function type() {
return $this->belongsTo('cap\ContactType');
}
}
联系型号:
class Contact extends CustomModel{
protected $dates = [...];
protected $fillable = [...];
protected static function boot(){
parent::boot();
static::addGlobalScope(new ValidScope());
}
public function departmentResponsibles() {
return $this->hasMany('cap\DepartmentResponsible');
}
}
ContactType型号:
class ContactType extends CustomModel {
protected $dates = [...];
protected $fillable = [...];
protected static function boot() {
parent::boot();
static::addGlobalScope(new ValidScope());
}
public function responsible() {
return $this->hasMany('cap\DepartmentResponsible');
}
}
部门模型:
class Department extends CustomModel {
protected $fillable = [...];
protected $dates = [...];
protected static function boot(){
parent::boot();
static::addGlobalScope(new ValidScope());
}
public function responsibles(){
return $this->hasMany('cap\DepartmentResponsible');
}
//other methods down here, which have no immpact on this issue
}
我现在可以做像
这样的事情Department::first()->responsibles
关于数据透视表上时间戳的问题,我假设我必须再次使它成为自定义数据透视表(已经不得不这样做一次,在另一种情况下,我有一个“常规”双向数据透视表)
现在我的2个问题是:
1。这甚至是正确的方法吗?我的意思是整个事情与中间模型等等。我也尝试了其他方法,但是因为我总是需要第三个ID而无法使用department->attach(contact)
之类的东西......
2。我怎样才能获得像Department :: first() - >联系人那样的工作?(在某种程度上,我可以访问中间“负责人(= contact_contact_type_department)”表并根据有效日期过滤;例如,使用范围或使用wherepivot函数)
答案 0 :(得分:0)
我终于采用了一种方法,即我有一个称为负责人的中间模型。因此,例如,如果我想打印一个部门的所有联系人及其contact_types,那么我可以这样做:
$department = Department::first();
<ul>
foreach($department->responsible as $responsible){
<li>{{$responsible->contact->name}} as {{$responsible->type->name}}</li>
}
</ul>