【问题标题】:Integrity constraint violation: 1048 Column 'postqs_id' cannot be null违反完整性约束:1048 列“postqs_id”不能为空
【发布时间】:2018-03-04 16:13:34
【问题描述】:

我有reply_qs 表和postqs 表。postqs_id 是reply_qs 表中的外键。当我尝试将reply_qs 表单数据保存在数据库中时,它显示此错误。

错误:

SQLSTATE[23000]:完整性约束违规:1048 列“postqs_id”不能为空(SQL:插入reply_qsreplypostqs_idupdated_atcreated_at)值(dd,,, 2017-09-23 02:54:16, 2017-09-23 02:54:16))

我该如何解决?并请解释为什么我会收到此错误。

reply_qs 模型:

 protected $table = 'reply_qs';
 protected $fillable = ['reply'];

 public function postqs(){
     return $this->hasMany('App\Postqs', 'postqs_id', 'id');
    }

postqs 模型:

  public function reply_qs(){
     return $this->hasMany('App\Reply_qs');
    }

存储功能:

public function store(Request $request) {
  $reply = new Reply_qs();
  $reply->reply = $request->get('reply');
  $reply->postqs_id = $request->get('postqs_id');
  $reply->save();

迁移:

   Schema::create('reply_qs', function (Blueprint $table) {
        $table->increments('id')->unique();
        $table->text('reply');
        $table->timestamps('date');
       });

   DB::statement('SET FOREIGN_KEY_CHECKS=0;');
    Schema::table('reply_qs',function(Blueprint $table)
    {
     $table->integer('postqs_id')->unsigned();
     $table->foreign('postqs_id')->references('id')->on('postqs') -
     >onDelete('cascade')->onUpdate('cascade');
    });

    DB::statement('SET FOREIGN_KEY_CHECKS=1;');

【问题讨论】:

  • 请为使用的语言和框架添加标签,因为这不仅仅是 SQL 直接到 MySQL
  • 疯狂的问题,但你真的得到postqs_id 的数据吗?还是那是NULL?
  • @cwallenpoole 它不为空..
  • 您只在一个表中将字段定义为not null。您必须将它们设置为相同:两个相关字段(来自reply_qsid 和来自Postqspostqs_id 需要是相同类型的 - 不能为空。
  • @Tpojka 它已经在表中的 NOT NULL 中。

标签: php mysql laravel foreign-keys


【解决方案1】:

你需要改变你们的关系。

在您的 reply_qs 模型中:

public function postqs(){
    return $this->belongsTo('App\Postqs', 'postqs_id', 'id');
}

【讨论】:

    猜你喜欢
    • 2020-03-29
    • 2018-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-20
    • 2021-08-16
    • 2019-10-06
    相关资源
    最近更新 更多