搜索所有记录,但只返回父元素'数据


Laravel 5.2 Search all records but return only parent elements' data

我编写了一个搜索函数,用于搜索数据库中所有帖子的名称和内容字段。这些帖子中有一些是有关的(父母和孩子)。我有一个问题,如果我的搜索返回命中在一个孩子的帖子,我想只返回父数据(尽量减少负载)。

My Post model:

public function children()
{
    return $this->hasMany('App'Post','parent_post_id','id');
}
public function children_count()
{
    return $this->children()
                ->selectRaw('parent_post_id, count(*) as answers')
                ->groupBy('parent_post_id');
}
public function parents()
{
    return $this->hasOne('App'Post','id','paren_post_id');
}
public function author()
{
    return $this->hasOne('App'User', 'id', 'user_id');
}

我的搜索查询:

$posts = Post::with('children')
->with('children_count')
->with('author')
->where('name','like','%'.$search_term.'%')
->orWhere('content','like','%'.$search_term.'%')
->orderBy('created_at','desc')
->groupBy('id')
->paginate(10);

示例:Post#1有两个子Post#2和Post#3。我的搜索在Post#3中找到数据,现在我希望它返回Post#1的数据。

编辑:

我知道我需要更多地解释我到底想要达到什么目标。

Posts表结构:

  • id
  • <
  • 名称/gh>
  • 蛞蝓
  • user_id
  • parent_post_id
  • updated_at
  • created_at

我正在搜索每个帖子的名称和内容字段(作者(user_id)此时不相关)。当搜索发现在子post命中(有parent_post_id设置为父母的id),我只想得到父母的数据(id,段塞,名称,内容等)

我可以这样做:

    $posts = DB::table('posts as a')
->leftJoin('posts as b', 'b.parent_post_id', '=', 'a.id')
->where('a.name','like','%'.$search_term.'%')
->orWhere('a.content','like','%'.$search_term.'%')
->orWhere('b.name','like','%'.$search_term.'%')
->orWhere('b.content','like','%'.$search_term.'%')
->select('a.*')->orderBy('a.created_at','desc')->paginate(10)

但是无法成功计数返回的父节点的所有子节点。这可能也会给一些关于如何用Laravel的方式来包装的想法

谁能给我指个正确的方向?

class Post extends Model{
public function children()
{
    return $this->hasMany(Post::class, 'parent_post_id', 'id');
}
public function children_count()
{
    return $this->children()
        ->selectRaw('parent_post_id, count(*) as answers')
        ->groupBy('parent_post_id');
}
public function parents()
{
    return $this->hasOne(Post::class, 'id', 'parent_post_id');
}
public function author()
{  
   return $this->hasOne(User::class, 'id', 'user_id');
}
}

  $posts = Post::with(['children_count', 'author', 'children'])
        ->whereHas('author', function ($query) use ($search_term) {
            $query->where('name', 'like', '%' . $search_term . '%');
        })
        ->orWhere('content','like','%' . $search_term . '%')
        ->orderBy('created_at', 'desc')
        ->paginate(10);