完整性約束違規:1452無法添加或更新子行:外鍵約束失敗(projects
。posts
,CONSTRAINT posts_user_id_foreign
FOREIGN KEY(user_id
)參考文獻users
(id
))我需要知道帖子的所有者,通過使用引用帖子中的表用戶的外鍵
class CreatePostsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->engine ='InnoDB';
$table->increments('id');
$table->string('jobtitle');
$table->string('location');
$table->string('jobtype');
$table->string('jobdesc');
$table->string('companyname');
$table->string('howto');
$table->integer('user_id')->unsigned();
$table->timestamps();
});
Schema::table('posts', function($table) {
$table->foreign('user_id')->references('id')->on('users');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('posts');
}
}
Post模型
class Posts extends Model
{
//
protected $fillable =[
'jobtitle',
'location',
'jobtype',
'jobdesc',
'companyname',
'howto',
'user_id'
];
protected $guarded = array();
public static $rules = array();
public function users()
{
return $this->belongsTo('App\User');
}
}
用戶模型
public function posts()
{
return $this->hasMany('App\Posts','user_id ');
}
我是laravel的新手 –
您的錯誤確實與Laravel無關,這是一個SQL錯誤,意味着您在插入時指定的posts.user_id不存在於users.id – Devon
您嘗試嘗試時發生此錯誤將數據插入表中? – ryantxr