在局部作用域的where子句中使用全局作用域(计数)

时间:2018-08-03 07:53:20

标签: sql laravel eloquent

我有带有多个标签的帖子,并已将posts_count作为全局范围添加到我的标签模型中

protected static function boot()
{
    parent::boot();

    static::addGlobalScope('postCount', function($builder) {
        $builder->withCount('posts');
    });
}

现在我要选择“热门”标签

 public function scopePopular($query)
{
    return $query->where('posts_count', '>', 1)
                 ->orderBy('posts_count', 'desc');
}

但是这不适用于消息

PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'posts_count' in 'where clause'

生成的查询看起来像

select `tags`.*, 
  (select count(*) 
  from `posts` 
  inner join `post_tag` 
  on `posts`.`id` = `post_tag`.`post_id` 
  where `tags`.`id` = `post_tag`.`tag_id`) 
as `posts_count` 
from `tags` 
where `posts_count` > 1 
order by `posts_count` desc

由于结果被选择为“ as posts_count”,我希望查询能够正常工作

更新:

标签表

    Schema::create('tags', function (Blueprint $table) {
        $table->increments('id');

        $table->string('name')->unique();

        $table->timestamps();
    });

    Schema::create('post_tag', function (Blueprint $table) {
        $table->integer('tag_id')->unsigned();
        $table->integer('post_id')->unsigned();

        $table->foreign('tag_id')
              ->references('id')
              ->on('tags')
              ->onDelete('cascade');

        $table->foreign('post_id')
              ->references('id')
              ->on('posts')
              ->onDelete('cascade');
    });

发布表

    Schema::create('posts', function (Blueprint $table) {
        $table->increments('id');

        $table->string('title');

        $table->string('slug')->unique();

        $table->text('image')->nullable();

        $table->string('status');

        $table->integer('user_id')->unsigned()->nullable();

        $table->foreign('user_id')
              ->references('id')
              ->on('users')
              ->onDelete('set null');

        $table->timestamps();

        $table->timestamp('published_at')->nullable();
    });

0 个答案:

没有答案