0
我有一個Laravel模型,它在我的登臺服務器中返回字符串值而不是整數。 我決定通過cast屬性的值來獲得總是整數的值。Laravel雄辯屬性Casting不起作用
我報我的模型:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class PressReviewPreset extends Model
{
/**
* Use soft delete
*/
use SoftDeletes;
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'pr_preset';
/**
* The attributes that should be mutated to dates.
*
* @var array
*/
protected $dates = ['deleted_at'];
/**
* The attributes that should be casted to native types.
*
* @var array
*/
protected $casts = [
'id' => 'integer',
'user_id' => 'integer',
'is_default' => 'integer',
];
/**
* The database field "updated_at" of table with a custom name
* @var string
*/
const UPDATED_AT = 'last_update';
/*
|---------------------------|
| Aliases for attribute |
|---------------------------|
*/
// Id
public function getIdAttribute()
{
return $this->attributes['id'];
}
public function setIdAttribute($id)
{
$this->attributes['id'] = $id;
}
// UserId
public function getUserIdAttribute()
{
return $this->attributes['user_id'];
}
public function setUserIdAttribute($user_id)
{
$this->attributes['user_id'] = $user_id;
}
// Default
public function getDefaultAttribute()
{
return $this->attributes['is_default'];
}
public function setDefaultAttribute($is_default)
{
$this->attributes['is_default'] = $is_default;
}
// ...
}
當我叫我的MacBook的工匠修補匠屬性我得到這個結果:
>>> $p = App\Models\PressReviewPreset::first()
=> App\Models\PressReviewPreset {#810
id: 41,
user_id: 391,
name: "DEMO",
is_default: 1,
last_update: "2017-03-10 14:32:39",
created_at: "2017-03-10 14:27:24",
deleted_at: null,
}
>>> $p->id
=> 41
>>> $p->user_id
=> 391
>>> $p->userId
=> 391
>>> $p->is_default
=> 1
>>> $p->default
=> 1
所有的值都是正確的整數。
但是,如果我把我的臨時服務器上相同的屬性我得到這個結果:
>>> $p = App\Models\PressReviewPreset::first()
=> App\Models\PressReviewPreset {#810
id: "41",
user_id: "391",
name: "DEMO",
is_default: "1",
last_update: "2017-03-10 14:32:39",
created_at: "2017-03-10 14:27:24",
deleted_at: null,
}
>>> $p->id
=> "41"
>>> $p->user_id
=> "391"
>>> $p->userId
=> "391"
>>> $p->is_default
=> 1
>>> $p->default
=> "1"
爲什麼user_id
沒有正確鑄造成整數?
我做錯了什麼?
在此先感謝!
關注此主題http://stackoverflow.com/questions/20079320/php-pdo-mysql-how-do-i-return-integer-and-numeric-columns-from-mysql-as-int – EddyTheDove
@EddyTheDove我很好奇,因爲我以前遇到過同樣的問題......儘管您鏈接的線程可能會詳細說明問題的根源,但是在模型填充後,Laravel的投射功能是否應該確保值正確地進行了類型轉換? – alaric
作爲解決方法,頑強的您是否嘗試過使用setXxxAttribute函數來轉換值? – alaric