mercredi 31 octobre 2018

Laravel morphedByMany return all records by where condition and count

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

I want get all district tags with count order by name.

I want it return an array like this:

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

I try do it by this:

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

but it return all (product) tags and all products_count values is 1 like this/:

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



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire