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

问题描述 投票:0回答:2

我有两张桌子,

cities
towns

我需要做的是查询这两个表,合并它们的结果,并按它们的

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 个结果。我也不确定这是否是最好的方法。

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

在我看来,我有这样的想法:

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

    @else (CHECK IF RESULT IS TOWN)

    @endif
@endforeach

如何查看哪条记录属于哪个表?

php laravel laravel-5 eloquent
2个回答
1
投票

合并 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);

如果你想知道该对象是哪个模型,你可以使用原生

is_a
function

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

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

    @endif
@endforeach

0
投票

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

$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
© www.soinside.com 2019 - 2024. All rights reserved.