代码之家  ›  专栏  ›  技术社区  ›  Sagar Chamling

Pull id(整数)转换为字符串Laravel

  •  9
  • Sagar Chamling  · 技术社区  · 7 年前

    当我从数据库中提取数据时 id 作为字符串。

    $alphabets = new Alphabet();
    return $alphabets->pluck('name', 'id');
    

    输出

    {
        "1": "Apple",
        "2": "Ball",
        "3": "Cat"
    }
    

    {
        1: "Apple",
        2: "Ball",
        3: "Cat"
    }
    

    但是,当我反转时 ID name ,

    return $alphabets->pluck('id', 'name');
    

    我得到的id是整数。

    {
        "Apple": 1,
        "Ball": 2,
        "Cat": 3
    }
    

    我不确定幕后发生了什么。但我怎样才能得到整数中的ID呢?实际上,旧的flash会话没有设置值,因为 1 vs "1" 以集体形式。

    {!! Form::select('alphabet', $alphabets, null, ['class' => 'form-control', 'multiple' => true]) !!}
    
    5 回复  |  直到 7 年前
        1
  •  7
  •   Dharmesh Rakholia    7 年前

    尝试此代码

    $alphabets = new Alphabet();
    return $alphabets->all()->pluck('name', 'id');
    

    Alphabet.php

    你应该这样投稿。

      protected $casts = [
        'id' => 'integer',
        'name' => 'string' 
      ];
    
        2
  •  3
  •   Sagar Chamling    7 年前

    https://laracasts.com/discuss/channels/laravel/pluck-id-integer-cast-to-string

    在这里,我发现JSON只允许键名是字符串。

    Using number as "index" (JSON)

    {
        "1": "Apple",
        "2": "Ball",
        "3": "Cat"
    }
    

    实际上,我想实现它 Form Collective 这是一个错误,它的公关现在已经合并。

    https://github.com/LaravelCollective/html/pull/368#pullrequestreview-46820423

        3
  •  1
  •   Shailesh Ladumor    7 年前

     $alphabets = new Alphabet();
        $alphaArr =$alphabets->pluck('name', 'id');
        foreach($array as $key => $value) {
           $newArray[(int) $key] = $value;
        }
    
        4
  •  0
  •   Sagar Gautam    7 年前

    pluck() 在字符串值中。

    select 这样的陈述:

    $data = Alphabet::select('id','name')->get()->toArray();
    

    array:3 [▼
      0 => array:2 [▼
        "id" => 1
        "name" => "Apple"
      ]
      1 => array:2 [▼
        "id" => 2
        "name" => "Ball"
      ]
      2 => array:2 [▼
        "id" => 3
        "name" => "Cat"
      ]
    ]
    

    $expected = array();
    
    foreach($data as $d){
        $expected[$d['name']] = $d['id'];
    }
    
    dd($expected);
    
        5
  •  0
  •   Sagar Chamling    7 年前

    添加此行修复了LaravelCollective/Html的旧会话问题。

    || in_array((string) $value, $selected, true)

    /**
     * Determine if the value is selected.
     *
     * @param  string $value
     * @param  string $selected
     *
     * @return null|string
     */
    protected function getSelectedValue($value, $selected)
    {
        if (is_array($selected)) {
            return in_array($value, $selected, true) || in_array((string) $value, $selected, true) ? 'selected' : null;
        } elseif ($selected instanceof Collection) {
            return $selected->contains($value) ? 'selected' : null;
        }
        return ((string) $value == (string) $selected) ? 'selected' : null;
    }