2017-06-28 25 views
6

Podczas wyodrębniania z bazy danych otrzymuję jako ciągi id.Pluck id (liczba całkowita) rzutuje na ciąg Laravel

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

Wyjście

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

Oczekiwany

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

Ale kiedy odwrócić ID i name,

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

Otrzymuję identyfikator jako liczbę całkowitą.

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

Nie jestem pewien, co dzieje się za sceną. Ale jak mogę uzyskać ID w liczbie całkowitej? W rzeczywistości stara sesja flash nie ustawia wartości z powodu 1 vs "1" w formularzu zbiorczym.

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

Odpowiedz

3

wypróbować ten kod

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

Alphabet.php

oddasz kolumn tak.

protected $casts = [ 
    'id' => 'integer', 
    'name' => 'string' 
    ]; 
+0

Ja już próbowałem to nie wydaje się działać. Ale dzięki. –

0

Zazwyczaj pluck() metoda daje asocjacyjną wartości w wartości ciągów.

Więc spróbuj select wypowiedzi tak:

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

To daje następujący wynik:

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

Teraz, stosując prostą pętlę można uzyskać oczekiwany tablicę.

$expected = array(); 

foreach($data as $d){ 
    $expected[$d['name']] = $d['id']; 
} 

dd($expected); 
+1

to drugi przypadek mojego pytania, ale to nie jest oczekiwany wynik. –

1

również przekonwertować klucz do int

$alphabets = new Alphabet(); 
    $alphaArr =$alphabets->pluck('name', 'id'); 
    foreach($array as $key => $value) { 
     $newArray[(int) $key] = $value; 
    } 
+0

Próbowałem również, ale wynik jest taki sam. Txs –

0

Dodawanie ta linia naprawić stary problem sesji dla 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; 
} 
Powiązane problemy