Laravel:使用foreach时,会话ID奇怪地被截断

时间:2016-06-29 03:37:39

标签: php laravel session eloquent

所以这有点奇怪......在Laravel 5.2中,我试图从sessions数据库表中检索id。我使用Artisan生成的默认Sessions迁移。

Session.php(会话模型,这就是我所拥有的):

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Session extends Model
{
    protected $table = 'sessions';
}

如果我$sessions = Session::where('user_id', Auth::user()->id)->get();并使用dd($sessions);查看嵌套数组,则显示完整的ID;例如402de1fd4c6f3a9bda5d4f4c5980e5748dcddbde。但是,当我做的时候

foreach($sessions as $session) {
    $id = $session->id;
}

执行dd($id);只截断字符串中任何字母前的第一个数字;在此示例中402。如果没有初始数字,则会返回0

为什么会发生这种情况有什么原因吗?不幸的是,由于我在运行dd之前没有操纵任何东西,我无法弄清楚这个字符串是怎么回事。

1 个答案:

答案 0 :(得分:1)

当您致电$session->id时,它会从您的模型中调用php magic method __get,然后从该方法调用getAttribute方法,然后getAttributeValuegetAttributeValue调用之后的一些其他方法检查hasCast然后从该方法调用getCastshttps://github.com/laravel/framework/blob/5.2/src/Illuminate/Database/Eloquent/Model.php#L2769-L2778

正如您在主键中看到的那样,它会添加默认广播int,因此对于您的问题,您可以cast

protected $casts = [ 'id' => 'string', ];//This part is taken from the comment of z3r0ck

或只是添加$keyType

protected $keyType = 'string';