Laravel:使用foreach时获取会话ID奇怪截断 [英] Laravel: Getting Session ID oddly truncates when using foreach

查看:131
本文介绍了Laravel:使用foreach时获取会话ID奇怪截断的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.php (Session Model, this is all I have):

<?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) / code>,完整ID显示;例如 402de1fd4c6f3a9bda5d4f4c5980e5748dcddbde 。但是,当我执行

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;
}

dd($ id); 截断到字符串中任何字母前的第一位数字;在这个例子中 402 。如果没有初始数字,则返回 0

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.

有什么原因可能会发生吗?不幸的是,由于我在运行 dd 之前没有操作任何东西,我无法弄清这个字符串发生了什么。

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.

推荐答案

当您调用 $ session-> id 时,它调用php magic方法 __ get 从你的模型,然后从该方法它调用 getAttribute 方法然后 getAttributeValue getAttributeValue 它调用一些其他方法后,它检查它 hasCast 然后它从该方法调用 getCasts https:// github。 com / laravel / framework / blob / 5.2 / src / Illuminate / Database / Eloquent / Model.php#L276​​9-L2778

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)

正如你所见对于主键,它会添加一个默认转换 int ,因此您的问题可以是 cast

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

的注释,或者只是添加 $ keyType

or just add $keyType

protected $keyType = 'string';

这篇关于Laravel:使用foreach时获取会话ID奇怪截断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆