Laravel为主键值返回零

时间:2017-08-14 00:53:58

标签: laravel laravel-5

我在这个laravel插入代码中遇到了问题。无论何时创建新公司,我都会在公司创建时获得输出,但是公司名称为0.我不知道为什么会发生这种情况。我的代码是

控制器:

public function store(Request $request)
    {

        $Company = new Company([
            'company_name' => $request->input('company_name'),
            'head'=>$request->input('head'),
            'Email'=>$request->input('email'),
            'address'=>$request->input('address'),
            'phno'=>$request->input('phno'),
            'contact_person'=>$request->input('contact_person')

        ]);
        if ($Company->save()) {

            $response = [
                'msg' => 'Company Created',
                'Company' => $Company
            ];
            return response()->json($response, 201);
        }
        $response = [
            'msg' => 'An Error Occurred',
        ];
        return response()->json($response, 502);
    }

我的模型代码是:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Company extends Model
{
    //
    protected $table = 'companies';
    public $timestamps = false;
    protected $primaryKey = 'company_name';
    protected $fillable = ['company_name','head','contact_person','phno','email','address'];

}

输入:

{
    "company_name":"cachii1",
    "head":"sankar",
    "email":"sankar@gmail.com",
    "address":"chennai",
    "phno":"123",
    "contact_person":"sankar"
}

输出:

{
    "msg": "Company Created",
    "Company": {
        "company_name": 0,
        "head": "sankar",
        "address": "chennai",
        "phno": "123",
        "contact_person": "sankar"
    }
}

数据库架构是 数据库架构是 数据库架构是

    public function up()
    {
        Schema::create('companies', function (Blueprint $table) {
           // $table->increments('company_id');
            $table->string('company_name');
            $table->primary('company_name');
            $table->string('head');
            $table->string('contact_person');
            $table->bigInteger('phno');
            $table->string('email');
            $table->text('address');

        });

1 个答案:

答案 0 :(得分:4)

默认情况下,Laravel希望您的模型主键自动递增。根据您发布的内容,您的示例看起来并非如此。

将此添加到您的模型定义中:

public $incrementing = false;