gpt4 book ai didi

php - 具有自定义枢轴模型的 Laravel 5.2 三向枢轴

转载 作者:行者123 更新时间:2023-11-29 03:25:02 24 4
gpt4 key购买 nike

我有以下问题:

我有三个表:

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 个问题是:

<强>1。这甚至是正确的方法吗?我指的是中间模型等的整个过程。我也尝试了其他方法,但我无法使用 department->attach(contact) 之类的东西,因为我也总是需要第三个 id...

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

最佳答案

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

$department = Department::first();

<ul>
foreach($department->responsible as $responsible){
<li>{{$responsible->contact->name}} as {{$responsible->type->name}}</li>
}
</ul>

关于php - 具有自定义枢轴模型的 Laravel 5.2 三向枢轴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37858309/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com