【发布时间】:2020-08-13 06:58:53
【问题描述】:
我目前正在通过个人项目学习 Laravel。
上下文
在类似博客的应用程序中,我需要将文章链接到其作者。当我保存文章时,我收到以下错误。
错误
SQLSTATE[23000]:完整性约束违规:1452 无法添加或更新子行:外键约束失败(
parabolica-dev.articles,CONSTRAINTarticles_user_id_foreignFOREIGN KEY(user_id)参考users(id)) (SQL: 插入articles(title,content,excerpt,updated_at,created_at) 值 (rgergregerg, regergergregerg, regregregregreg, 2020-04-29 09: 55:12, 2020-04-29 09:55:12))
型号
文章
class Article extends Model
{
protected $fillable = ['title', 'content', 'excerpt', 'user_id'];
public function user() {
return $this->belongsTo('App\User');
}
}
用户
class User extends Authenticatable
{
protected $fillable = [
'name', 'email', 'password',
];
public function article()
{
return $this->hasMany('App\Article');
}
}
迁移
用户
class CreateUsersTable extends Migration
{
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('users');
}
}
文章
class CreateArticlesTable extends Migration
{
public function up()
{
Schema::create('articles', function (Blueprint $table) {
$table->id();
$table->timestamps();
$table->string('title');
$table->text('excerpt');
$table->text('content');
$table->string('type');
$table->string('status');
// Relationship between article and user
$table->bigInteger('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
});
}
public function down()
{
Schema::dropIfExists('articles');
}
}
控制器
文章控制器
class ArticleController extends Controller
{
public function store(StoreArticle $request)
{
$validatedData = $request->validated();
$user = Auth::user()->id;
$article = Article::create($validatedData);
$article->user_id = $user;
$request->session()->flash('status', 'Article was created!');
return redirect()->route('articles.show', ['article' => $article->id]);
}
}
尝试的解决方案
- 在我的 Article 模型中将 user_id 添加到 $fillable 数组中,我仍然收到错误。
- 在我的迁移中将 nullable() 方法添加到 user_id。保存文章没有错误消息,但之后 user_id 在我的表中记录为空。
根据我的发现,这些是跨 SO / LaravelCast 提出最多的 2 个解决方案。关于我做错了什么有什么建议吗?
谢谢你帮助我!
【问题讨论】: