我目前正在通过个人项目学习 Laravel。
Context
在类似博客的应用程序中,我需要将文章链接到其作者。当我保存文章时,出现以下错误。
Error
SQLSTATE[23000]:违反完整性约束:1452 无法添加或更新子行:外键约束失败(parabolica-dev
.articles
, 约束articles_user_id_foreign
外键(user_id
) 参考users
(id
)) (SQL: 插入articles
(title
, content
, excerpt
, updated_at
, created_at
)值(rgergregerg、reggergregerg、regregregregreg、2020-04-29 09:55:12、2020-04-29 09:55:12))
Models
Article
class Article extends Model
{
protected $fillable = ['title', 'content', 'excerpt', 'user_id'];
public function user() {
return $this->belongsTo('App\User');
}
}
User
class User extends Authenticatable
{
protected $fillable = [
'name', 'email', 'password',
];
public function article()
{
return $this->hasMany('App\Article');
}
}
迁移
Users
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');
}
}
Articles
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]);
}
}
尝试过的解决方案
- 将 user_id 添加到我的文章模型中的 $fillable 数组中,我仍然收到错误。
- 在我的迁移中将 nullable() 方法添加到 user_id 中。保存文章时没有出现错误消息,但随后 user_id 在我的表中记录为 null。
根据我的发现,这些是 SO / LaravelCasts 中最受提议的 2 个解决方案。对我做错了什么有什么建议吗?
谢谢你帮助我!