【问题标题】:Error: Object of class App\Http\Resources\ProductAttributeResource could not be converted to int错误:类 App\Http\Resources\ProductAttributeResource 的对象无法转换为 int
【发布时间】:2020-07-01 06:53:43
【问题描述】:

我在我的模型中使用方法来改变对我的客户的单个响应

什么时候默认使用这个方法名调用产品Laravel?

/**
 * Returns product attributes data to use in the API response.
 *
 * @return \Illuminate\Http\Resources\Json\AnonymousResourceCollection
 */
public function getAttributes()
{
    return ProductAttributeResource::collection($this->attributes);
}

调试器显示这个区域:

C:\xampp\htdocs.../...\vendor\Laravel\framework\src\Illuminate\Database\Eloquent\Concerns\HasAttributes.php:521

protected function castAttribute($key, $value)

{
    $castType = $this->getCastType($key);

    if (is_null($value) && in_array($castType, static::$primitiveCastTypes)) {
        return $value;
    }
    switch ($castType) {
        case 'int':
        case 'integer':
            return (int) $value;
        case 'real':

我该如何解决这个错误?

【问题讨论】:

    标签: php laravel debugging eloquent laravel-7.x


    【解决方案1】:

    在我的例子中,我在模型中使用了保留的方法名称

    例如,我为我的一对多关系定义了一个新的属性()方法,我应该为它选择另一个名称

    只需将您的 getAttributes 重命名为模型中的 getAttribute 方法

    因为这个名字被模型类使用

    【讨论】:

    • 我在我的模型中使用 attribute() 方法。只需要重命名该方法 laravel 使用 attribute() 并覆盖。但我想将我的模型连接到属性表。
    猜你喜欢
    • 2018-04-20
    • 1970-01-01
    • 2021-08-15
    • 2022-08-16
    • 2019-05-02
    • 2017-03-08
    • 2019-01-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多