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

时间:2016-10-05 19:18:33

标签: laravel laravel-5 eloquent laravel-5.3

我有两个表,citiestowns

我需要做的是查询这两个表,合并结果,并按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

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

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分: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