Laravel morphedByMany通过条件和计数返回所有记录

时间:2018-10-31 14:00:41

标签: laravel laravel-5 eloquent laravel-query-builder

db.get("PRAGMA foreign_keys = ON")

我想获取所有按名称计数顺序不同的标签。

我希望它返回这样的数组:

Table 1: products: id, title, publish,created_at
Table 2: tags: id,name,created_at
Table 3: taggable: id,tag_id,taggable_type,taggable_id

我试图这样做:

[
  ['name1'=>'value1','count'=>3],
  ['name2'=>'value2','count'=>3]
]

但是它返回所有($tags = \App\Tag::distinct()->where( function( $query ){ $query->whereHas('products', function ( $subquery ){ $subquery->where('publish', 1 ); })->get()->toarray(); })->withCount('products')->get()->toarray(); )标签,并且所有product的值都是1,如下所示:

products_count

编辑:

 [...],
 [▼
    "id" => 75
    "name" => "test1"
    "created_at" => "2018-10-30 18:49:51"
    "products_count" => 1
  ],
  [...]
  ...

enter image description here

1 个答案:

答案 0 :(得分:0)

withCount('products')必须先被调用,distinct()必须是->get()->toArray()之前的最后一个。

尝试一下(虽然未测试):

$tags = \App\Tag::withCount('products')->where( function( $query ){
                   $query->whereHas('products', function ( $subquery ){
                       $subquery->where('publish', 1 );
                   })->get()->toArray();
                 })->distinct()->get()->toArray();