【发布时间】:2021-03-20 16:56:08
【问题描述】:
我有以下型号 类型->类别->任务
哪里类别可以属于不同的类型。 这里我在 Category Model 中使用了 morphTo
类别模型
class Category extends Model {
public function categorize(){
return $this->morphTo();
}
public function tasks(){
return $this->belongsToMany(Task::class,'task_category');
}
public function types(){
return $this->belongsTo(Type::class);
}
}
在类型中我使用 morphMany
class Type extends Model
{
//
protected $fillable = [
'slug'
];
public function categories(){
return $this->morphMany(Category::class,'categorize');
}
public function project(){
return $this->belongsTo(Project::class);
}
/* public function tasks(){
return $this->hasManyThrough(
Task::class,
Category::class,
);
} */
}
这按预期工作,但我不知道我在任务控制器中如何通过类型模型根据类型和所有类别获取所有任务。我尝试了hasManyThrough,但它不起作用,因为任务和类别是通过数据透视表关联的。
目前我有
$type = Type::with('categories')->where('slug', $type)->first();
这让我得到了带有类别的类型,但如前所述,我想在每个类别对象下获得相关的任务。 如果有什么不清楚的地方,我很乐意澄清和纠正任何需要的东西。非常感谢所有帮助。
【问题讨论】: