如何对两个具有不同模型的合并集合进行排序

时间:2019-01-29 22:36:00

标签: laravel laravel-5 eloquent

我有两个模型CitiesStates。一个City有1个State,一个State可以有0个或多个Cities。我需要分别检索所有CitiesStates,因为即使一个州没有相关城市,也需要显示州(例如,下例中的阿拉巴马州)。问题是,我需要先按州名排序,然后再按该州的城市(如果有)进行排序

城市

id, state_id, name 
1, 1, San Diego 
2, 1, Hollywood
3, 2, Seattle
4, 3, Pheonix

状态

id, name
1, California
2, Washington 
3, Arizona
4, Alabama 

控制器:

$cities = Cities::with('state')->get(); // Returns the state relationship 
$states = States::get();

$merged = $states->merge($cities);

我现在想先按State的名称排序,然后按该State的所有城市排序,并返回类似于以下内容的合并集合:

{
    id: 4,
    name: Alabama,
}, 
{
    id: 3,
    name: Arizona,
}, 
{
    id: 3,
    name: Pheonix,
    state_id: 3
    state: {
        id: 3,
        name: Arizona
    }
},
{
    id: 1,
    name: California
},
{
    id: 2,
    name: Hollywood
    state_id: 1,
    state: {
        id: 1,
        name: California
    }
},
{
    id: 1,
    name: San Diego,
    state_id: 1,
    state: {
        id: 1,
        name: California
    }
}, 
{
    id: 2,
    name: Washington,

},
{
    id: 2,
    name: Seattle,
    state_id: 2,
    state: {
        id: 2,
        name: Washington
    }
}

1 个答案:

答案 0 :(得分:0)

我认为您可以执行以下查询:

$states = State::all()->sortBy('name'); // Here your sort by the state name first

如果您建立了正确的关系,则可以从每个州访问城市,如下所示:(您无需合并馆藏):

@foreach($states as $state)  // this will sort the cities by id
{{$state->cities}}
@endforeach

要按名称对它们进行排序,可以尝试以下操作:


@foreach($states as $state)  
{{$state->cities->sortBy('name')}}
@endforeach