采用多列?

问题描述 投票:9回答:6

当我使用多列的pluck时,我得到这个:

{"Kreis 1 \/ Altstadt":"City","Kreis 2":"Enge","Kreis 3":"Sihifeld","Kreis 4":"Hard","Kreis 5 \/ Industriequartier":"Escher Wyss","Kreis 6":"Oberstrass","Kreis 7":"Witikon","Kreis 8 \/ Reisbach":"Weinegg","Kreis 9":"Altstetten","Kreis 10":"Wipkingen","Kreis 11":"Seebach","Kreis 12 \/ Schwamendingen":"Hirzenbach"

但我需要这个吗?

["Rathaus","Hochschulen","Lindenhof","City","Wollishofen","Leimbach","Enge","Alt-Wiedikon","Friesenberg","Sihifeld","Werd","Langstrasse","Hard","Gewerbechule","Escher Wyss","Unterstrass","Oberstrass","Fluntern","Hottingen","Hirslanden","Witikon","Seefeld","M\u00fchlebach","Weinegg","Albisrieden","Altstetten","H\u00f6ngg","Wipkingen","Affoltern","Oerlikon","Seebach","Saatlen","Schwamendingen-Mitte","Hirzenbach"]

任何建议我怎么能这样做?这是我的方法:

    public function autocomplete_districts(Request $request)
   {
      $district = $request->input('query');
      // $ass = /DB::table('districts')->select(array('district', 'region'))->get();
      // dd($ass);
      $data = Districts::whereRaw('LOWER(district) like ?', [strtolower('%'.$district . '%')])->orWhereRaw('LOWER(region) like ?', [strtolower('%'.$district . '%')])->pluck('region','district');

      return response()->json($data);
   }
laravel laravel-5 laravel-5.2
6个回答
6
投票

这就是采摘的方式。而是试试这个。

$data = Districts::whereRaw('LOWER(district) like ?', [strtolower('%'.$district . '%')])->orWhereRaw('LOWER(region) like ?', [strtolower('%'.$district . '%')])->select('region', 'district')->get();

$data = collect($data->toArray())->flatten()->all();

18
投票

您应该将select()get()一起使用,然后根据需要修改对象。

因此,而不是:->pluck('region','district');使用:->select('region','district')->get();

当您只需要一列的价值时,建议使用pluck()

并且尽可能地,你应该让你的模型单数形式而不是复数(区) - 遵循Laravel命名法。


2
投票

这是我经常遇到的一个问题,并使我创建了可用于模型或阵列的以下解决方案。 还支持点语法,它将根据需要创建多维数组。

AppServiceProvider(或您选择的任何提供商)中注册此宏:

/**
 * Similar to pluck, with the exception that it can 'pluck' more than one column.
 * This method can be used on either Eloquent models or arrays.
 * @param string|array $cols Set the columns to be selected.
 * @return Collection A new collection consisting of only the specified columns.
 */
    Collection::macro('pick', function ($cols = ['*']) {
    $cols = is_array($cols) ? $cols : func_get_args();
    $obj = clone $this;

    // Just return the entire collection if the asterisk is found.
    if (in_array('*', $cols)) {
        return $this;
    }

    return $obj->transform(function ($value) use ($cols) {
        $ret = [];
        foreach ($cols as $col) {
            // This will enable us to treat the column as a if it is a
            // database query in order to rename our column.
            $name = $col;
            if (preg_match('/(.*) as (.*)/i', $col, $matches)) {
                $col = $matches[1];
                $name = $matches[2];
            }

            // If we use the asterisk then it will assign that as a key,
            // but that is almost certainly **not** what the user
            // intends to do.
            $name = str_replace('.*.', '.', $name);

            // We do it this way so that we can utilise the dot notation
            // to set and get the data.
            array_set($ret, $name, data_get($value, $col));
        }

        return $ret;
    });
});

然后可以按以下方式使用它:

$a = collect([
    ['first' => 1, 'second' => 2, 'third' => 3],
    ['first' => 1, 'second' => 2, 'third' => 3]
]);

$b = $a->pick('first', 'third'); // returns [['first' => 1, 'third' => 3], ['first' => 1, 'third' => 3]]

或者,您可以在任何型号上:

$users = User::all();
$new = $users->pick('name', 'username', 'email');
// Might return something like:
// [
//     ['name' => 'John Doe', 'username' => 'john', 'email' => '[email protected]'],
//     ['name' => 'Jane Doe', 'username' => 'jane', 'email' => '[email protected]'],
//     ['name' => 'Joe Bloggs', 'username' => 'joe', 'email' => '[email protected]'],
// ]

也可以使用点表示法引用任何关系,以及使用as [other name]语法:

$users = User::all();
$new = $users->pick('name as fullname', 'email', 'posts.comments');
// Might return something like:
// [
//     ['fullname' => 'John Doe', 'email' => '[email protected]', 'posts' => [...]],
//     ['fullname' => 'Jane Doe', 'email' => '[email protected]', 'posts' => [...]],
//     ['fullname' => 'Joe Bloggs', 'email' => '[email protected]', 'posts' => [...]],
// ]

0
投票

Laravel:要在单独的数组中插入多列,请使用以下代码。

$Ads=Ads::where('status',1);
$Ads=$Ads->where('created_at','>',Carbon::now()->subDays(30));
$activeAdsIds=$Ads->pluck('id'); // array of ads ids
$UserId=$Ads->pluck('user_id'); // array of users ids

0
投票

我在LARAVEL 5.6中的解决方案:

嗨,我刚遇到同样的问题,我需要在1个选择列表中合并2列。我的数据库有2列用户:first_name和last_name。我需要一个选择框,用户全名可见,id为值。这就是我使用pluck()方法修复它的方法:

在User模型中,我创建了一个全名访问器函数:

public function getNameAttribute() {
    return ucwords($this->last_name . ' ' . $this->first_name);
}

之后,要使用全名和相应的数据库ID作为值填充选择列表,我在我的控制器中使用此代码返回视图(不显示已存档的用户,但如果您愿意,可以更改查询的开头)最重要的是get()和pluck()函数:

$users = User::whereNull('archived_at')
    ->orderBy('last_name')
    ->get(['id','first_name','last_name'])
    ->pluck('name','id');
return view('your.view', compact('users'));

现在您可以在选择列表中使用$ users!

首先,您需要从DB中获取所需的所有值,之后您可以使用为PLUCK方法定义的任何访问器属性,

只要访问者所需的所有列都在GET中;-)


0
投票

我创建了模型范围

有关范围的更多信息:

码:

/**
 * Scope a query to Pluck The Multiple Columns
 *
 * This is Used to Pluck the multiple Columns in the table based
 * on the existing query builder instance
 *
 * @author Manojkiran.A <[email protected]>
 * @version 0.0.2
 * @param  \Illuminate\Database\Eloquent\Builder $query
 * @param string $keyColumn the columns Which is used to set the key of array
 * @param array $extraFields the list of columns that need to plucked in the table
 * @return \Illuminate\Support\Collection
 * @throws Illuminate\Database\QueryException
 **/
public function scopePluckMultiple( $query, string $keyColumn, array $extraFields):\Illuminate\Support\Collection
{
    //pluck all the id based on the query builder instance class
    $keyColumnPluck = $query->pluck( $keyColumn)->toArray();
    //anonymous callback method to iterate over the each fileds of table
    $callBcakMethod = function ($eachValue) use ($query)
    {
        $eachQuery[$eachValue] = $query->pluck( $eachValue)->toArray();
        return $eachQuery;
    };
    //now we are collapsing the array single time to get the propered array 
    $extraFields = \Illuminate\Support\Arr::collapse( array_map($callBcakMethod, $extraFields));

    // //iterating Through All Other Fields and Plucking it each Time
    // foreach ((array)$extraFields as  $eachField) {
    //         $extraFields[$eachField] =   $query->pluck($eachField)->toArray();
    //     }

    //now we are done with plucking the Required Columns
    //we need to map all the values to each key

    //get all the keys of extra fields and sets as array key or index
    $arrayKeys = array_keys($extraFields);
    //get all the extra fields array and mapping it to each key
    $arrayValues = array_map(
        function ($value) use ($arrayKeys) {
            return array_combine($arrayKeys, $value);
        },
        call_user_func_array('array_map', array_merge(
            array(function () {
                return func_get_args();
            }),
            $extraFields
        ))
    );
    //now we are done with the array now Convert it to Collection
    return collect( array_combine( $keyColumnPluck, $arrayValues));
}

所以现在是测试部分

基本范例

$basicPluck  = Model::pluckMultiple('primaryKeyFiles',['fieldOne', 'FieldTwo']);

高级示例

$advancedPlcuk  = Model::whereBetween('column',[10,43])
                            ->orWhere('columnName','LIKE', '%whildCard%')
                            ->Where( 'columnName', 'NOT LIKE', '%whildCard%')
                            ->pluckMultiple('primaryKeyFiles',['fieldOne', 'FieldTwo']);

但它返回\ Illuminate \ Support \ Collection,所以如果你需要转换为数组

$toArrayColl = $advancedPluck->toArray();

如果你需要转换为json

$toJsonColl = $advancedPluck->toJson();
© www.soinside.com 2019 - 2024. All rights reserved.