查询两个表并根据 created_at 合并结果

Query two tables and combine results based on created_at

我有两个 table,citiestowns

我需要做的是查询这两个 table,合并它们的结果,并按它们的 created_at 列排序。此外,我需要将其限制为总共 25 个结果。在我的视图中显示它们时,我还需要以某种方式区分哪些记录属于 cities,哪些属于 towns

这就是我目前所拥有的,但我认为这不是正确的做法:

$cities = City::orderBy('created_at', 'DESC')
    ->get();

$towns = Town::orderBy('created_at', 'DESC')
    ->get();

$results = array_merge($cities->toArray(), $towns->toArray());
usort($results, function($a, $b)
{
    return $a['created_at'] < $b['created_at'];
});

return $results;

问题是它没有将结果限制为总共 25 个。我也不确定这是否是最好的方法。

我需要解决的第二个问题是在我的视图中显示结果。我需要一种方法来区分哪个记录属于哪个 table.

在我看来,我有这样的东西:

@foreach ($results as $result)
    @if (CHECK IF RESULT IS CITY)

    @else (CHECK IF RESULT IS TOWN)

    @endif
@endforeach

如何查看哪条记录属于哪条 table?

合并 2 个收集结果,然后按日期降序排列,然后取 25 个

$cities = City::orderBy('created_at', 'DESC')
    ->get();

$towns = Town::orderBy('created_at', 'DESC')
    ->get();
$merged = $cities->merge($towns);

然后对它们进行排序

$sorted = $collection->sortByDesc('created_at');

终于拿下25个

$results = $sorted->take(25);

如果你想知道对象是哪个模型你可以使用native is_a function

@foreach ($results as $result)
    @if (is_a($result, \App\City::class))

    @else (is_a($result, \App\Town::class))

    @endif
@endforeach

我不确定这是否有效,因为我还没有测试过,但我觉得应该

$cities = City::orderBy('id', 'desc')->limit(25)->get();

$towns = Town::orderBy('id', 'desc')->limit(25)->get();

$citiesAndTowns = $cities->merge($towns)->sortByDesc('created_at')->take(25);

// or use sortBy('created_at') for ascending....

现在在视图中你可以简单地这样做...

@foreach($citiesAndTowns as $cityOrTown)
  @if(get_class($cityOrTown) == 'App\City')

  @else

  @endif
@endforeach

或者要跳过那种肮脏的做事方式,您可以 $citiesAndTowns->toArray() 并像这样在视图中进行更改...

@foreach($citiesAndTowns as $cityOrTown)
  // Since `city_id` will never be a part of city table and even if
  // it is null in Town, it will still be set....
  @if(isset($cityOrTown['city_id'])) 

  @else

  @endif
@endforeach