所以这有点奇怪......在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
之前没有操纵任何东西,我无法弄清楚这个字符串是怎么回事。
答案 0 :(得分:1)
当您致电$session->id
时,它会从您的模型中调用php magic method __get
,然后从该方法调用getAttribute
方法,然后getAttributeValue
从getAttributeValue
调用之后的一些其他方法检查hasCast
然后从该方法调用getCasts
(https://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';