我有三个模型记录,类别和子类别。记录表将category_id和subcategory_id存储为外键。有一个数据透视表“ category_subcategory”。
我想通过模型中的自定义函数以一种优雅而高效的方式检索所有具有“ 无效类别子类别关系”的记录。
“ 无效的类别子类别关系”是什么意思:
使用模型中的此自定义函数,我希望能够在Controller中执行以下操作:
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);
}
}
答案 0 :(得分:1)
Laravel提供whereNotExists
,在这里可能会有所帮助。
为Record
模型添加以下功能:
// Adjust the func name as per your test ;)
public function scopeInvalidRecords($query)
{
return $query->whereNotExists(function($q) {
$q->select(\DB::raw(1))
->from('category_subcategory')
->whereRaw('
category_subcategory.category_id = records.category_id
AND
category_subcategory.subcategory_id = records.subcategory_id
');
});
}
在控制器中:
Record::invalidRecords()->get();
// It'll give you all the invalid records(invalid as per your definition)
希望有帮助!
答案 1 :(得分:0)
由于@Zeshan Khattak,我得以得到所需的东西。现在我得到了满足a)b)c)的“无效”记录
public function scopeInvalidRecords($query)
{
return $query->whereExists(function($q) {
$q->select(\DB::raw(1))
->from('category_subcategory')
->whereRaw('
category_subcategory.category_id = records.category_id
');
})->whereNotExists(function($q) {
$q->select(\DB::raw(1))
->from('category_subcategory')
->whereRaw('
category_subcategory.category_id = records.category_id
AND
category_subcategory.subcategory_id = records.subcategory_id
');
})->orWhereNotExists(function($q) {
$q->select(\DB::raw(1))
->from('category_subcategory')
->whereRaw('
category_subcategory.category_id = records.category_id
');
})->whereNotNull('subcategory_id');
}