Php 拉威尔收集范围
因为这个问题,我很痛苦。 问题 我有Php 拉威尔收集范围,php,laravel,Php,Laravel,因为这个问题,我很痛苦。 问题 我有categories表,其中包含id、slug和parent\u id 课程表,其中包含类别id(类别的子级) 我想通过雄辩的范围获得Categoryparentid 例如: id=1的父类具有id3、4和5的子类 然后在父类别id=1,下检索Lessons,因此必须返回所有孩子的课程 类别表 Lessons.php return Lesson::recentLessons()
categories
表,其中包含id
、slug
和parent\u id
课程
表,其中包含类别id
(类别的子级)
我想通过雄辩的范围获得Category
parentid
例如:
id=1的父类具有id3
、4
和5
的子类
然后在父类别id=1
,下检索Lesson
s,因此必须返回所有孩子的课程
类别表
Lessons.php
return Lesson::recentLessons()
->byParentCategory($args['category'])
->simplePaginate($page)
->shuffle();
如何构造scopeByParentCategory()函数
很抱歉这个模糊的问题!花了3个小时尝试:(
更新:我在发布问题后就有了这个想法,但仍然想知道你对此有何看法,以及这是否是处理问题的最佳方式
public function scopeByParentCategory($query, $slug)
{
$ids = [];
foreach (Category::where('slug', $slug)->first()->children as $value)
{
$ids[] = $value->id;
}
return $query->whereIn('category_id', $ids);
}
首先将此代码放入您的类别中
型号:
public function scopeOfSlug($query, $slug)
{
$query->where('slug', $slug);
}
然后在你的控制器里
return Category::ofSlug($args['category'])
->lessons
->simplePaginate($page)
->shuffle();
谢谢你在短时间内回答,但我想在课程中应用其他范围。你能用你已经编写的代码更新你的问题吗?
return Category::ofSlug($args['category'])
->lessons
->simplePaginate($page)
->shuffle();