duangu1868 2018-05-17 10:20
浏览 35
已采纳

使用Laravel的Eloquent查询构建

I'm trying to code a search functionality which not only allows me to search by a category of a question but also by its content. I'm using PostgreSQL and its ts_vector capabilities for the content. For the categories, I want to use Laravel's Eloquent and Query Builder.

The content search is fully working, but I can't figure out how to limit the displayed questions to the ones with those categories. This is what I have so far:

$questions = Question::search($query_string)->paginate(NUM_PER_PAGE);

I also have an array of strings which are category names ($tag_names). As you can see from the schema each name is unique.

This is the schema:

CREATE TABLE questions (
    id BIGINT PRIMARY KEY REFERENCES commentables(id) ON DELETE CASCADE,
    title TEXT NOT NULL,
    correct_answer BIGINT UNIQUE,
    search tsvector
);

CREATE TABLE categories (
    id SERIAL PRIMARY KEY,
    name TEXT NOT NULL UNIQUE,
    description TEXT,
    num_posts INTEGER DEFAULT 0 NOT NULL
);

CREATE TABLE questions_categories (
    question_id BIGINT REFERENCES questions(id) ON DELETE CASCADE,
    category_id INTEGER REFERENCES categories(id) ON DELETE CASCADE,
    PRIMARY KEY (question_id, category_id)
);

I've created the Model Classes for each of the database tables, so you can refer to them by Question, Category and QuestionsCategory.

  • 写回答

1条回答 默认 最新

  • dongshun5963 2018-05-19 16:28
    关注

    Define a categories relationship in your Question model:

    public function categories() {
        return $this->belongsToMany(Category::class, 'questions_categories')
    }
    

    Then extend your query:

    $questions = Question::search($query_string)
        ->whereHas('categories', function($query) use($categoryIds) {
            $query->whereIn('id', $categoryIds);
        })->paginate(NUM_PER_PAGE);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分