具有空主键值的雄辩模型

时间:2018-10-01 14:00:02

标签: php eloquent slim-3

我正在将Slim 3与Eloquent用作ORM。我有一个产品表,其中仅包含3个字段,productCode,名称和价格。我在获取产品属性时遇到问题。

我为产品创建了一个模型类,如下所示:

class Product extends Model
{
    protected $primaryKey = 'productCode';

    public $timestamps = false;

    protected $fillable = [
        'name',
        'price'
    ];
}

Esi la estoy utilizando desde mi controlador para enviarlos como Json,de la siguiente forma:

class ProductsController extends Controller
{

    public function getAll($request, $response)
    {
        $products = Product::all();

        return $response->withJson($products, 200);
    }
}

问题在于它返回以下内容:

[{"productCode":0,"name":"producto 1","price":15000},{"productCode":0,"name":"producto 2","price":20000},{"productCode":0,"name":"producto 3","price":5999}]

所有productCode变量均被更改为真空,因此json返回0。

当使用print_r()复查变量时,它确实包含正确的productCode,但是我无法获取这些值,它始终返回空。

    Store\Models\Product Object
(
    [primaryKey:protected] => productCode
    [timestamps] => 
    [fillable:protected] => Array
        (
            [0] => name
            [1] => price
        )

    [connection:protected] => default
    [table:protected] => 
    [keyType:protected] => int
    [incrementing] => 1
    [with:protected] => Array
        (
        )

    [withCount:protected] => Array
        (
        )

    [perPage:protected] => 15
    [exists] => 1
    [wasRecentlyCreated] => 
    [attributes:protected] => Array
        (
            [productCode] => cod0001
            [name] => producto 1
            [price] => 15000
        )

    [original:protected] => Array
        (
            [productCode] => cod0001
            [name] => producto 1
            [price] => 15000
        )

    [changes:protected] => Array
        (
        )

    [casts:protected] => Array
        (
        )

    [dates:protected] => Array
        (
        )

    [dateFormat:protected] => 
    [appends:protected] => Array
        (
        )

    [dispatchesEvents:protected] => Array
        (
        )

    [observables:protected] => Array
        (
        )

    [relations:protected] => Array
        (
        )

    [touches:protected] => Array
        (
        )

    [hidden:protected] => Array
        (
        )

    [visible:protected] => Array
        (
        )

    [guarded:protected] => Array
        (
            [0] => *
        )

)

如您所见,如果变量包含正确的productCode,问题是当我尝试获取它们时它们仍然为空。

1 个答案:

答案 0 :(得分:2)

您必须告诉Eloquent主键不是自动递增:

class Product extends Model
{
    public $incrementing = false;
}