【发布时间】:2019-11-28 13:46:52
【问题描述】:
我有三个模型Record、Category和Subcategory。 Record 表将 category_id 和 subcategory_id 存储为外键。有一个数据透视表“category_subcategory”。
我想通过模型中的自定义函数以优雅且高效的方式检索具有“无效的类别子类别关系”的所有记录。
“无效的类别子类别关系”是什么意思:
- a) 记录具有类别和子类别。但子类别不属于类别(数据透视表中没有条目)
- b) 记录有一个类别但没有子类别(subcategory_id = NULL)。因为Category本身有Subcategories,所以Record的subcategory_id应该为NULL
- c) Record有Category和Subcategory,但是Cateory本身没有Subcategories,因此Record应该有subcategory_id = NULL
通过模型中的这个自定义函数,我希望能够在控制器中做这样的事情:
Records::withInvalidCategorySubcategoryRelation()->get(); //or similar
而不是像在 Controller 中那样经历无穷无尽的 foreach 循环
$records = Record::all();
foreach($records as record){ ...
非常感谢任何建议!
这是我的模型类:
class Record extends Model
{
public function category()
{
return $this->belongsTo(Category::class);
}
public function subcategory()
{
return $this->belongsTo(Subcategory::class);
}
}
class Category extends Model
{
public function subcategories()
{
return $this->belongsToMany(Subcategory::class);
}
}
class Subcategory extends Model
{
public function categories()
{
return $this->belongsToMany(Category::class);
}
}
【问题讨论】:
标签: laravel eloquent model pivot-table