0

我正在尝试使用以下查询查询国家/地区表以打印具有相应城市的所有国家/地区。现在我为每个城市获得一个重复的国家对象,而不是为所有城市拥有一个国家对象。

$all = ORM::factory('country')->select('cities.*')->join('cities','LEFT')->on('country.id', '=', 'country_id' )->find-all();

foreach ($all as $country) {
    echo $caountry->name;
    foreach($country->cities as $city ){
        echo $city->name;
    }
}

感谢您的帮助,AA

4

1 回答 1

0

如果您使用 MySQL 并且只需要城市名称,您可以使用GROUP_CONCAT函数,然后使用 PHP 的 explode 将其转换为数组。

    $all = ORM::factory('country')
    ->select('country.name',DB::epxr('GROUP_CONCAT(cities.name) AS cities'))
    ->join('cities','LEFT')
    ->on('country.id', '=', 'country_id' )
    ->group_by("country.id")
    ->find-all();

foreach ($all as $country) {
    echo $country->name;
    foreach(explode(",",$country->cities) as $city ){
        echo $city;
    }
}
于 2012-05-01T14:49:33.030 回答