gpt4 book ai didi

php - Laravel Eloquent 属性转换不起作用

转载 作者:行者123 更新时间:2023-12-03 19:39:06 26 4
gpt4 key购买 nike

我有一个 Laravel 模型,它在我的登台服务器中返回字符串值而不是整数。
我决定cast属性的值以始终获得整数值。

我报告我的模型:

<?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 的 artisan tinker 中调用属性时,我得到以下结果:
>>> $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没有正确转换为整数?

我做错了什么吗?

提前致谢!

最佳答案

在你的属性中,你再次施放它呢?

public function getIdAttribute()
{
return (int) $this->attributes['id'];
}

运气好的话?

关于php - Laravel Eloquent 属性转换不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42828142/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com