@wim91 I tried to reproduce your situation on my app. My models are:
- Project -> BelongsToMany -> Person
- Person -> BelongsToMany -> Project
I added lvl column to persons table.
I added some code to my Project model:
// I had it before
public function persons (): BelongsToMany
{
return $this->belongsToMany(Person::class)->using(PersonProject::class)->withPivot('id', 'role')->withTimestamps();
}
// added now
public function lvl1()
{
return $this->persons()->where('lvl', '=', 1)->inRandomOrder()->limit(3);
}
public function lvl2()
{
return $this->persons()->where('lvl', '=', 2)->inRandomOrder()->limit(2);
}
public function result_relation()
{
return $this->lvl1()->union($this->lvl2());
}
And working code is:
$project = Project::find(1);
$result = $project->result_relation()->get()->shuffle();
foreach($result as $r) {
echo "model: " . get_class($r) . ", id: {$r->id}, lvl: {$r->lvl}" . "\n";
}
Launched it several times, it seems the result is exactly what you asked: five models, three with lvl = 1, two with lvl = 2, in random order.
c:\nastroim\pipka>php artisan app:test
model: App\Models\Person, id: 5, lvl: 1
model: App\Models\Person, id: 6, lvl: 2
model: App\Models\Person, id: 8, lvl: 1
model: App\Models\Person, id: 1, lvl: 1
model: App\Models\Person, id: 7, lvl: 2
c:\nastroim\pipka>php artisan app:test
model: App\Models\Person, id: 5, lvl: 1
model: App\Models\Person, id: 1, lvl: 1
model: App\Models\Person, id: 7, lvl: 2
model: App\Models\Person, id: 6, lvl: 2
model: App\Models\Person, id: 4, lvl: 1
c:\nastroim\pipka>php artisan app:test
model: App\Models\Person, id: 5, lvl: 1
model: App\Models\Person, id: 2, lvl: 2
model: App\Models\Person, id: 3, lvl: 2
model: App\Models\Person, id: 8, lvl: 1
model: App\Models\Person, id: 4, lvl: 1