9

从数据库中提取时,我得到id字符串。

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

输出

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

预期的

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

但是,当我反转IDand时name

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

我得到 id 作为整数。

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

我不确定幕后发生了什么。但是我怎样才能得到整数 ID 呢?实际上,旧的 Flash 会话没有设置值,因为1 vs "1"在 Form Collective 中。

{!! Form::select('alphabet', $alphabets, null, ['class' => 'form-control', 'multiple' => true]) !!}
4

5 回答 5

6

试试这个代码

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

字母表.php

你应该像这样投射你的专栏。

  protected $casts = [
    'id' => 'integer',
    'name' => 'string' 
  ];
于 2017-06-28T11:11:18.673 回答
3

我想我在这里找到了答案。

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

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

使用数字作为“索引”(JSON)

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

实际上,我想为Form Collective. 这是一个错误,现在它的 PR 已被合并。

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

于 2017-06-28T12:37:23.807 回答
1

您还将 key 转换为 int

 $alphabets = new Alphabet();
    $alphaArr =$alphabets->pluck('name', 'id');
    foreach($array as $key => $value) {
       $newArray[(int) $key] = $value;
    }
于 2017-06-28T11:22:29.307 回答
0

通常,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);
于 2017-06-28T11:19:34.537 回答
0

添加此行修复了 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;
}
于 2017-06-30T18:02:37.957 回答