问题
So this is something a little weird... In Laravel 5.2, I'm trying to retrieve the id from the sessions database table. I'm using the default Sessions migration generated by Artisan.
Session.php (Session Model, this is all I have):
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Session extends Model
{
protected $table = 'sessions';
}
If I do $sessions = Session::where('user_id', Auth::user()->id)->get();
and look through the nested arrays using dd($sessions);
, the full ID shows up; for example 402de1fd4c6f3a9bda5d4f4c5980e5748dcddbde
. However, when I do
foreach($sessions as $session) {
$id = $session->id;
}
doing dd($id);
truncates to only the first digits before any letters in the string; in this example 402
. If there are no initial digits, 0
is returned instead.
Is there any reason why this would be happening? Unfortunately, since I'm not manipulating anything before running dd
I cannot figure out what's going on with this string.
回答1:
When you call $session->id
it calls php magic method __get
from your model then from that method it calls getAttribute
method then getAttributeValue
from getAttributeValue
it calls some other methods after that it checks it hasCast
then it calls getCasts
from that method (https://github.com/laravel/framework/blob/5.2/src/Illuminate/Database/Eloquent/Model.php#L2769-L2778)
As you can see there for primary key it adds a default cast int
so for your problem you can either cast
protected $casts = [ 'id' => 'string', ];//This part is taken from the comment of z3r0ck
or just add $keyType
protected $keyType = 'string';
来源:https://stackoverflow.com/questions/38089965/laravel-getting-session-id-oddly-truncates-when-using-foreach