【问题标题】:Laravel 5.2 three-way pivot with custom pivot modelLaravel 5.2 三向枢轴与自定义枢轴模型
【发布时间】:2016-07-27 17:56:47
【问题描述】:

我有以下问题:

我有三张桌子:

contacts (people)
departments
contact_types (e.g. IT-Contact)

都是多对多类型;一个人可以作为 0-n 个 Contact_types 负责 0-n 个部门(即使是同一个部门作为多个类型)。等等。

此外,我必须拥有整个项目的历史,因此每个表还存储“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 向数据透视表)

所以我现在的 2 个问题是:

1.这甚至是正确的方法吗?我的意思是中间模型等等。我也尝试了其他方法,但我无法让department->attach(contact) 之类的东西工作,因为我也总是需要第三个 id...

2。我怎样才能让 Department::first()->contacts 之类的东西工作?(在某种程度上,我可以访问中间的“responsibles (=contact_contact_type_department)”表并根据有效期进行过滤;例如. 带有作用域或带有 wherepivot 函数)

【问题讨论】:

    标签: php mysql laravel laravel-5.2


    【解决方案1】:

    好吧,我终于采用了一种方法,即我有一个称为责任的中间模型。因此,例如,如果我想打印一个部门的所有联系人及其contact_types,那么我可以这样做:

    $department = Department::first();
    
    <ul>
        foreach($department->responsible as $responsible){
            <li>{{$responsible->contact->name}} as {{$responsible->type->name}}</li>
        }
    </ul>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-17
      • 2012-05-02
      • 1970-01-01
      相关资源
      最近更新 更多