mercredi 5 octobre 2016

Query two tables and combine results based on created_at

I have two tables, cities and towns.

What I need to do is query these two tables, combine their results, and order them by their created_at columns. Additionally, I need to limit it to a total of 25 results. I also need to somehow distinguish which record belongs to cities and which belongs to towns when displaying them in my view.

This is what I have at the moment, but I don't think it's the right way of doing it:

$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;

The problem with this is that it doesn't limit it to a total of 25 results. I'm also not sure if it's the best way of doing it.

The second problem I need to solve is displaying the results in my view. I need a way to distinguish which record belongs to which table.

In my view, I have something like:

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

    @else (CHECK IF RESULT IS TOWN)

    @endif
@endforeach

How can I check which record belongs to which table?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire