dongyinju5977 2018-04-17 06:46
浏览 152
已采纳

Eloquent create表示列使用Laravel 5没有默认值

I have an small API that i want to save into client mysql database. For this purpose i'm using guzzle.

my controller:

 public function index()
    {
        $http = new \GuzzleHttp\Client;
        $res = $http->request('GET', 'http://localhost:8080/api/address');
        $addresses = json_decode($res->getBody(),true);   
        // dd($addresses);
        Address::create($addresses);
    }

my model:

class Address extends Model
{
    protected $primaryKey = 'Adresse';
    protected $fillable = ['Adresse', 'Mandant', 'Kategorie', 'Matchcode', 'Name1'];

    public $timestamps = false;

}

my migration:

public function up()
{
   Schema::create('addresses', function (Blueprint $table) {
        $table->integer('Adresse')->primary();
        $table->smallInteger('Mandant');
        $table->smallInteger('Kategorie')->nullable();
        $table->string('Matchcode', 50);
        $table->string('Anrede', 50)->nullable();
        $table->string('Name1', 50)->nullable();
   });
}

my api content:

[
{"Adresse":"1111","Mandant":"0","Kategorie":"0","Matchcode":"fgh8881","Anrede":"Firma","Name1":"Sample name"},{"Adresse":"2399","Mandant":"0","Kategorie":"0","Matchcode":"fgh8882","Anrede":"Firma","Name1":"Sample name 1"}
]

the problem is i get an error

SQLSTATE[HY000]: General error: 1364 Field 'Adresse' doesn't have a default value (SQL: insert into addresses () values ())

when i limit the api content to one array i can save it without a problem. But if i have more arrays in my api i get this error. $fillable property on the model is set.

  • 写回答

4条回答 默认 最新

  • dsxsou8465 2018-04-17 07:50
    关注

    If your primary key is not auto-incrementing the framework needs to know about it.

    class Address extends Model
    {
        protected $primaryKey = 'Adresse';
        protected $fillable = ['Adresse', 'Mandant', 'Kategorie', 'Matchcode', 'Name1'];
        public $incrementing = false;
    
        public $timestamps = false;
    
    }
    

    Then to add all of the models:

    public function index()
    {
        $http = new \GuzzleHttp\Client;
        $res = $http->request('GET', 'http://localhost:8080/api/address');
        $addresses = json_decode($res->getBody(),true);   
        foreach ($addresses as $address) {
             Address::create($address);
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀