mercredi 17 février 2016

How to get a random model with at least N related of multiple `hasmany` models

I am trying to combine two features: - getting a random model - ... but only if it has at least 1 related model

my URL is entity/random and the below code works well:

    if ($entityid == 'random') {
        $random = Entity::all()->random(1);
        return Redirect::to(trans('routes.entities') . '/' . $random->id);
    }

Now, my Entity model has two relations defined:

public function comments()
{
    return $this->hasMany('App\Models\Comment', 'entity_id');
}

public function sources()
{
    return $this->hasMany('App\Models\Source', 'entity_id');
}

Having them defined, I can get the number of related comments by $object->comments->count() or sources by $object->sources->count(). My database is MySQL.

The majority of my Entities have NO comments nor sources.

Inspired by Laravel Querying Relations Model::has('relation') doesn't work i was able to get a random model with at least 2 comments:

$random = Entity::has('comments', '>=', DB::raw(2))->get()->random(1);
// produces an Entity with at least 2 comments

TO DO

How to pick a random model only if at least one of two relations count (sources OR comments) are at least 2. Maybe sth like orHas exists?




Aucun commentaire:

Enregistrer un commentaire