Ent*_*ity 0 php laravel eloquent
好吧,这是我的迁移......
public function up()
{
Schema::create('instagrams', function (Blueprint $table) {
$table->bigInteger('id')->unsigned()->primary();
// ...
});
}
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->bigInteger('instagram_id')->unsigned()->nullable();
// ...
});
}
Run Code Online (Sandbox Code Playgroud)
我有一个用户模型和一个 Instagram 模型。这是我的 Instagram 模型:
class Instagram extends Model
{
public function user()
{
return $this->hasOne('App\User');
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是 Instagram 与用户的关系不起作用。我无法从 Instagram 访问用户,即使他们都在数据库中。
>>> $u = App\User::first()
=> App\User {#695
id: 1,
instagram_id: "3620243170",
}
>>> $i = App\Instagram::first()
=> App\Instagram {#696
id: "3620243170",
}
>>> $i->user
=> null
Run Code Online (Sandbox Code Playgroud)
所以,我花了很长时间绞尽脑汁,直到找到这些有用的修补方法......这就是它给我的:
>>> $i->user()->toSql()
=> "select * from `users` where `users`.`instagram_id` = ? and `users`.`instagram_id` is not null"
>>> $i->user()->getBindings()
=> [
2147483647,
]
Run Code Online (Sandbox Code Playgroud)
一切都按顺序进行,除了 ID 被隐藏在 Laravel 中的任何代码限制在 32 位之外……ID 需要大于 32 位,因为这就是 Instagram 的 ID 的存储方式。我怎样才能让这种关系发挥作用?
听起来您使用的是 32 位版本的 PHP,其中最大整数值为 2147483647。
问题是,当关系查询获取实例的键值Instagram来查询用户时,它会自动将该 id 值转换为$keyType模型上的属性定义的类型。该属性是int默认的。
因此,即使您的Instagram实例 id 是"3620243170",它也会被转换为 int ,这在 32 位 PHP 中会将其转换为2147483647。
您可以尝试采取以下几项措施来缓解此问题:
使用 64 位版本的 PHP。64 位 PHP 的最大 int 大小与有符号 bigint 字段可用的最大 int 大小相匹配。但是,如果您使用的是未签名的 bigint,一旦您的 id 超过 9223372036854775807(不太可能),您将再次遇到此问题。
将模型$keyType上的属性更改Instagram为float或 可能string。这只会影响 Eloquent 在 PHP 中对变量的转换,不会影响它们在数据库中的存储方式。
添加protected $keyType = 'float';到您的Instagram模型。