【问题标题】:Relationship laravel with unique count具有唯一计数的关系 laravel
【发布时间】:2023-01-19 03:21:57
【问题描述】:

我在通过按列对元素进行分组来创建包含另一个表中元素计数的查询时遇到问题。

我试着用这个例子来解释这个问题:

表帖

id Title
1 first
2 second

表格视图

id post_id view_id
1 1 1
2 1 1
3 2 1
4 2 1
5 1 2
6 1 2

后模型

class Post extends Model{

  protected $table = 'post';

  protected $primaryKey = 'id';

  protected $fillable = [
    'title'
  ];

  public function related_views(){

    return $this->hasMany(Views::class, 'post_id', 'id');

  }

}

视图模型

class Views extends Model{

  protected $table = 'views';

  protected $primaryKey = 'id';

  protected $fillable = [
    'post_id',
    'view_id'
  ];

}

询问

$query = Post::with([
                'related_views' => function ($query) {
                    return $query->groupBy('view_id');
                }
            ])
            ->withCount('related_views')
            ->get();

查询已正确执行。在返回的多维数组中,除了主表中的列外,还有以下 2 个值:related_views 和 related_views_count。

related_views_count 变量对所有元素进行计数,而 related_views 变量仅按分组显示元素。

是否可以获取 related_views 变量中元素的计数而不是获取元素数组?

我希望我已经正确地陈述了我的问题。

【问题讨论】:

    标签: jquery mysql laravel eloquent eloquent-relationship


    【解决方案1】:

    您可以受益于 laravel's related models counting function 并将您的条件定义为闭包函数。

    $query = Post::withCount([
                    'related_views as related_views_grouped_count' => function ($query) {
                        return $query->groupBy('view_id');
                    }
                ])
            ->get();
    

    【讨论】:

    • 非常感谢您的回答。我尝试了您的解决方案,但出现此错误:“致命错误:未捕获的 PDOException:SQLSTATE [21000]:违反基数:1242 子查询返回超过 1 行”
    【解决方案2】:

    通过这个查询,我解决了问题!

    Post::query()
      ->withCount('related_views', function($query) {
              $query->select(DB::raw('count(distinct(view_id))'));
      })
    ->get();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-10
      • 1970-01-01
      • 2021-08-31
      • 1970-01-01
      • 2016-04-07
      • 2011-11-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多