Код: Выделить всё
competitions: id, name, synchronized_id
fixtures: id, competition_id
[*] конкуренция y - исходная. Y при поддержке дополнительных запросов на приспособлениях.
Код: Выделить всё
Competition → hasOne('synchronizedTo', Competition::class)
Competition → hasMany(Fixture::class)
< /code>
[b] Цель: < /strong> < /p>
Запрос всех оригинальных соревнований с агрегированными приспособлениями от себя и их дубликатов. n < /code> - это количество соревнований. < /li>
< /ul>
Текущий подход: < /strong> < /p>
Нагрузка конкурентов в массиве [оригинал_ид, Synchronized_to_id] < /code>. Несколько запросов, которые становятся неэффективными по мере роста соревнований. Union
Код: Выделить всё
with('fixtures')
еще не изучал пользовательские отношения. />
Код: Выделить всё
class Competition extends Model
{
public function synchronizedTo(): HasOne
{
return $this->hasOne(Competition::class, 'synchronized_id');
}
public function fixtures(): HasMany
{
return $this->hasMany(Fixture::class);
}
}
< /code>
И вот мой метод службы приспособления, который группируется по конкуренции: < /p>
private function groupByCompetition(array $data): array
{
$competitions = $this->competitionRepository
->newQuery()
->withoutSynchronization()
->with(['synchronizedTo' => fn($q) => $q->select(['id', 'synchronized_id'])])
->select(['id', 'synchronized_id', 'name', 'uuid'])
->orderByDesc('geo_country_id')
->orderByDesc('created_at')
->take(10)
->get();
$fixturesByCompetition = [];
foreach ($competitions as $competition) {
$fixturesByCompetition[$competition->id] = [
'ids' => [],
'name' => $competition->name,
'uuid' => $competition->uuid
];
$ref = &$fixturesByCompetition[$competition->id]['ids'];
$ref[] = $competition->getKey();
if (isset($competition->synchronizedTo)) {
$ref[] = $competition->synchronizedTo->getKey();
}
}
return collect($fixturesByCompetition)
->map(function ($competition) use ($data) {
return [
'title' => $competition['name'],
'id' => $competition['uuid'],
'grouped_by' => $data['group_by'],
'data' => $this->repository->toCollection(
$this->repository
->newQuery()
->whereIn('competition_id', $competition['ids'])
->selectQuery()
->halfRelationQuery()
->sellable()
->withoutSynchronization()
->filter($data)
->limit($data['limit'] ?? 20)
->offset($data['offset'] ?? 0)
->get()
)->resolve()
];
})
->filter(fn($item) => !empty($item['data']))
->values()
->toArray();
}
Код: Выделить всё
Competitions Table:
id | name | synchronized_id
---|-----------------------|----------------
1 | YFL | 2
2 | Youth Football League | null
Fixtures Table:
home_team | away_team | competition_id | date
----------------|-------------------|----------------|---------
ajax | liverpool | 1 | 2023-01-01
inter | milan | 1 | 2023-01-04
juventus | manchester city | 2 | 2023-01-02
latzio | real madrid | 2 | 2023-01-03
< /code>
$competitions = Competition::where('synchronized_id', null)
->with([
'fixtures' => fn($q) => $q->orderByDesc('date')->limit(2),
'synchronizedTo.fixtures' => fn($q) => $q->orderByDesc('date')->limit(2)
])->get();
$competitions->map(fn($c) => [
'fixtures' => $c->fixtures->merge($c->synchronizedTo->fixtures)
]);
Подробнее здесь: https://stackoverflow.com/questions/795 ... mpetitions