mercredi 31 août 2016

How to do statistics about a pivot table

I successfully defined a many-to-many relation:

// in model 'Label'
public function pictures() {
    return $this->belongsToMany('App\Picture');
}

// in model 'Picture'
public function labels() {
    return $this->belongsToMany('App\Label')->withTimestamps();
}

With this I can - for instance - easily retrieve the labels of a specific picture

$picture = Picture::find(1);
$labels = $picture->labels()->orderBy('name')->get();

But now I want to figure out how often each label is used. I could walk through all pictures, using the above code, but this would be inefficient.

Is there a way to do this in a better way and access the pivot table directly? ... something like

$n = DB::getPivot('App\Label', 'App\Pictures')->count()->groupBy('App\Label');

?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire