Русское сообщество разработки на PHP-фреймворке Laravel.
Ты не вошёл. Вход тут.
Страницы 1
Не получается создать комментарии вот ошибка:
QueryException in Connection.php line 651:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`newqe.dev`.`comments`, CONSTRAINT `comments_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE) (SQL: insert into `comments` (`updated_at`, `created_at`) values (2015-12-23 17:11:16, 2015-12-23 17:11:16))
Контроллер:
public function store(Request $request, $question_id)
{
$qe = Question::where('id', '=', $question_id)->first();
$commentData = array_merge($request->all(), ['user_id' => auth()->id()]);
$comment = comments::create($commentData);
$qe->comments()->save($comment);
}
Миграция
public function up()
{
Schema::create('comments', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->integer('question_id')->unsigned();
$table->foreign('question_id')->references('id')->on('questions')->onDelete('cascade');;
$table->text('comment');
$table->timestamps();
$table->rememberToken();
});
}
Форма:
<form action="{{ action('CommendsController@store') }}" method="POST" class="form-horizontal">
{{ csrf_field() }}
<div class="form-inline">
<input type="text" class="form-control" name="comment">
<button type="submit" class="btn btn-success" style="margin-left: 10px">Создать</button>
</div>
</form>
а оно находит $qe = Question::where('id', '=', $question_id)->first(); ???
ты б проверял найденное, а то мож там null
Не в сети
Действительно, был null переписал, контроллер
public function store(Request $request, $id)
{
$this->validate($request, [
'comment' => 'required|min:5'
]);
$commentReq=$request->all();
$commentReq['question_id'] = $id;
$commentData = array_merge($commentReq, ['user_id' => auth()->id()]);
comments::create($commentData);
}
вот что в $commentData
array:4 [▼
"_token" => "ybfzGG100AgkqDtw95INJv7FxsGN2ZfxELsqKD7S"
"comment" => "текст"
"question_id" => "13"
"user_id" => 1
]
все верно, но в базу не записывает, выходит
QueryException in Connection.php line 651:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`newqe.dev`.`comments`, CONSTRAINT `comments_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE) (SQL: insert into `comments` (`updated_at`, `created_at`) values (2015-12-24 12:26:13, 2015-12-24 12:26:13))
Страницы 1