【发布时间】:2018-06-21 03:54:43
【问题描述】:
我有一个添加评论的功能:
public function addComment(Request $request)
{
$request->validate([
'body' => 'required',
]);
$entry = new Comment();
$entry->body = $request->body;
$entry->save();
return redirect('/');
}
我还需要传入电影表 id,在 cmets 表中称为film_id。该字段不能为空。上面没有考虑这个字段,所以我收到以下消息:
SQLSTATE[23000]:违反完整性约束:19 NOT NULL 约束失败:cmets.film_id(SQL:插入“cmets” ("body", "updated_at", "created_at") 值
我尝试通过执行以下变体来传递电影 ID,但没有成功。
public function addComment(Request $request, $id)
{
$request->validate([
'body' => 'required',
'film_id' => 'required',
]);
$entry = new Comment();
$film_id = Film::find($id);
$entry->body = $request->body;
$entry->film_id = $film_id;
$entry->save();
return redirect('/');
评论模型:
class Comment extends Model
{
public function film()
{
return $this->belongsTo(Film::class);
}
}
电影模型:
class Film extends Model
{
public function comments()
{
return $this->hasMany(Comment::class);
}
}
【问题讨论】:
-
您的
Comment模型中是否有$guarded或$fillable,它是否指定film_id是否可填充或受保护?因为好像没有指定。 -
我刚刚将模型信息添加到问题中。我没有使用过 $guarded 或 $fillable。我对这些不熟悉。这是我想要达到的要求吗?
-
您必须添加数组,请参见此处:laravel.com/docs/5.5/eloquent - 我喜欢使用 $guarded,然后如果我使用它们,我会保留 'id' 和时间戳。跨度>
-
你能告诉我们你向服务器发出的请求吗?
标签: php sql laravel function controller