【问题标题】:How to Select one address for each different country in Laravel Eloquent如何在 Laravel Eloquent 中为每个不同的国家选择一个地址
【发布时间】:2021-06-04 05:47:14
【问题描述】:

我有一个数据库,其中有多个地址。 我需要为数据库中的每个不同国家/地区获取一行。 例如,如果我有 |编号 |姓名 |专栏 |国家 | | -- | -------------- | ------ | -------- | | 1 |主要地址 | 10 |英国 | | 2 |第二地址 | 3 |法国 | | 3 |第三地址 | 78 |美国 | | 4 |第四地址 | 46 |法国 | | 5 |第五地址 | 44 |法国 | | 6 |第六地址 | 11 |英国 | 我只需要检索 3 行:英国 1 行,法国 1 行,美国 1 行。我为每个国家/地区获得的行并不重要,但我需要完整的行。 (对于 UK id 1 或 6 无关紧要,但我需要所有列)。 我如何在 Laravel 中做到这一点(最好使用 Eloquent)。

我不能使用 group by,因为所有列都有不同的值...

【问题讨论】:

    标签: mysql laravel eloquent


    【解决方案1】:

    根据你的数据集有多大(如果非常大,这将变得低效)你可以做这样的事情......

    //Select and get the countries column.  
    $countries = DB::table('addresses')->select('country')->get();
    
    //Get the unique values of countries from the collection
    $uniqueCountries = $countries->unique();
    
    //Array which will contain a single address from each country.
    $singleAddresses = [];
    
    //Loop over each unique country you retrieved from the database.
    foreach($uniqueCountries as $country){
        //Grab the first address to occur for whatever country is currently being iterated over in the loop.
        $singleAddress = DB::table('addresses')->where('country','=',$country)->first();
        
        //Push the first address found for the country into the array of single addresses from various countries.
        array_push($singleAddresses,$singleAddress);
    }
    
    //Dump the array of collection to the page to make sure the output is what you want.
    dump($singleAddresses);
    

    基本上,您只需通过select statement. 从数据库中获取国家列,然后将这些数据作为集合返回给您。然后,您可以在该集合中使用 unique method 获取国家/地区名称的所有唯一实例。

    获得唯一的国家/地区名称列表后,您就可以继续获取每个国家/地区的地址。这是通过一次循环遍历一组独特的国家来完成的。发出数据库请求以仅选择该县所在的地址,然后获取该国家/地区内地址的第一个实例。

    一旦您拥有该地址数据的对象,您就需要将其推送到一个数组中,该数组包含您检索到的国家/地区的所有其他单个地址。

    循环完成后,您将拥有一组 Laravel 集合对象,其中包含来自数据库中每个国家/地区的单个地址。

    其他一些注意事项...

    【讨论】:

      【解决方案2】:

      我设法使用ANY_VALUE 来避免不同值的问题,并使用AS 来轻松使用这些字段。

      $addresses = Address::select(DB::raw('ANY_VALUE(name) AS name, ANY_VALUE(column) AS column'), 'country')->groupBy('country')->distinct()->get();
      

      它给了我一个数组,每个国家都有一行。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-03-30
        • 2022-01-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多