Sql 展平laravel嵌套关系(父代到子代)获取所有子代

Sql 展平laravel嵌套关系(父代到子代)获取所有子代,sql,database,laravel,Sql,Database,Laravel,这是我的控制器 $categoryIds = Category::select('id')->with('childrenRecursive')->where('id', 1)->get(); Ad::whereIn('category_id', $categoryIds)->get(); 这是我的型号 public function parent() { return $this->belongsTo(Category::class, 'parent_

这是我的控制器

$categoryIds = Category::select('id')->with('childrenRecursive')->where('id', 1)->get();
 Ad::whereIn('category_id', $categoryIds)->get();
这是我的型号

public function parent() {
    return $this->belongsTo(Category::class, 'parent_id');
}

public function childs() {
    return $this->hasMany(Category::class, 'parent_id');
}

public function Ads() {
    return $this->hasManyThrough(Ad::class, Category::class, 'parent_id', 'category_id', 'id');
}

如何获取所有儿童类别IDE

如果我正确理解您的问题,您还需要获取与给定类别记录的所有相关记录的id对应的广告

$category=category::with('childs:id,parent\u id'))
->其中('id',1)
->firstOrFail();
$categoryIds=collect([$category->parent_id,$category->id]);
$category->child->map(fn($child)=>$categoryIds->push($child->id));
$ads=ads::其中('category_id',$categoryID->filter()->all())
//如果需要,可以加载产品吗
//->带(‘产品’)
->get();

我会使用Laravel的子查询方法

$parentId = 4;

Ad::whereIn('category_id', function($q) use ($parentId) {
   $q->select('id')
     ->from('categories')
     ->where('parent_id', $parentId);
});
如果要添加父模型,可以使用()链接


您的代码块不清晰,因此您可能需要调整我的代码示例。

我使用此解决方案解决了此问题

我的控制器

public function index()
{
    $parent = Category::with('descendants')->find(1);
    $descendants = $this->traverseTree($parent, collect([1]));
    $ads = Ad::whereIn('category_id',$descendants)->get();
    return response($ads);
}

    protected function traverseTree($subtree, $des)
    {
        $descendants = $des;
        if ($subtree->descendants->count() > 0) {
            foreach ($subtree->descendants as $descendant) {
                $descendants->push($descendant);
                $this->traverseTree($descendant, $descendants);

            }
        }
        return $descendants;
    }

我可以获取所有产品继承类别id此查询仅获取具有父id的产品
public function index()
{
    $parent = Category::with('descendants')->find(1);
    $descendants = $this->traverseTree($parent, collect([1]));
    $ads = Ad::whereIn('category_id',$descendants)->get();
    return response($ads);
}

    protected function traverseTree($subtree, $des)
    {
        $descendants = $des;
        if ($subtree->descendants->count() > 0) {
            foreach ($subtree->descendants as $descendant) {
                $descendants->push($descendant);
                $this->traverseTree($descendant, $descendants);

            }
        }
        return $descendants;
    }