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
  ],
  [...]
  ...



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2PChNPS
via IFTTT

Aucun commentaire:

Enregistrer un commentaire