照亮\数据库\QueryException:SQLSTATE [HY000]:一般错误:
第1364章 'user_id'字段没有默认值
(连接:mysql,SQL:插入(posts
,post
,updated_at
)值(Bruhhhh,2024-05-25 12:35:55,2024-05-25 12:35:55)) 在文件中created_at
C:\Users\Bence\Downloads ackend endor\laravel ramework\src\Illuminate\Database\Connection.php
813线
为什么我在这条路线的邮递员中收到此错误? http://127.0.0.1:8000/api/posts/ 发帖
x-www-form-urlencoded
关键:发帖
价值:噗噗
在此示例项目中,我使用 laravel 数据库人员 和邮递员来测试 CRUD 方法。
这个简单的项目正在处理人的评论和数据库中的帖子,您可以使用邮递员添加新的帖子和评论数据库,如果可以的话,您可以使用邮递员删除,更新或读取。
逐步设置
composer create-project laravel/laravel example-app
php artisan i api
php artisan make:model model_name -mfsc
迁移表
Schema::create('posts', function (Blueprint $table) {
$table-\>id();
$table-\>foreignId('user_id')-\>constrained('users');
$table-\>string("post");
$table-\>timestamps();
});
//用户模型
public function posts(): HasMany
{
return $this-\>hasMany(Post::class);
}
public function comments(): HasMany
{
return $this-\>hasMany(Comment::class);
}
//post model
public function user(): BelongsTo
{
return $this-\>belongsTo(User::class);
}
可填写示例
protected $fillable = \[
'user_id',
'post'
\];
工厂示例
User::factory(5)
\-\>has(Post::factory(3))
\-\>has(Comment::factory(3))
\-\>create();
岗位控制器:
<?php
namespace App\Http\Controllers;
use App\Models\Post;
use Illuminate\Http\Request;
class PostController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index()
{
$posts = Post::all();
return response()->json($posts);
}
/**
* Create a resource in storage.
*/
public function store(Request $request)
{
$post = Post::create($request->all());
return response()->json(['success' => $post->id.' has been created.']);
}
/**
* Display the specified resource.
*/
public function show($id)
{
$post = Post::find($id);
return response()->json($post);
}
/**
* Update the specified resource in storage.
*/
public function update(Request $request, $id)
{
$post = Post::find($id);
$post->update($request->all());
return response()->json($post->id . ' has been updated.');
}
/**
* Remove the specified resource from storage.
*/
public function destroy($id)
{
Post::destroy($id);
return response()->json($id . ' has been deleted.');
}
}
API.php
Route::resource('/posts', PostController::class);
将您的存储方法调整为类似这样的
public function store(Request $request)
{
$post = Post::create([
'user_id'=>auth()->id()
'post'=>$request->post,
]);
return response()->json(['success' => $post->id.' has been created.']);
}
我假设用户在创建帖子时经过身份验证,如果不是这种情况,那么您必须在迁移中使
user_id
字段可为空
$request->all()
被认为非常不安全,问题是您在迁移过程中 user_id
字段不可为空,而您没有将其传递给查询,这就是它显示该错误的原因
了解更多关于 Laravel Eloquent 这里