提问人:vishwajeetpanwar 提问时间:6/14/2022 最后编辑:vishwajeetpanwar 更新时间:3/14/2023 访问量:1294
Laravel 在添加新条目时将当前用户的 ID 添加到表中
Laravel add the ID of current user into the table when he adds a new entry
问:
是的,所以我有一个带有用户 ID 的用户表和另一个避难所表,用户会将避难所添加到表中,我想显示将该特定避难所添加到我正在使用的表中的人员的用户 ID $table->foreignId('id')->references('id')->on('users');这给了我 SQLSTATE[HY000]:常规错误:1364 字段“id”没有默认值
避难所桌
public function up()
{
Schema::create('animal_shelters', function (Blueprint $table) {
$table->id('shelter_id');
$table->timestamps();
$table->foreignId('id')->references('id')->on('users');
$table->string('shelter_name');
$table->string('shelter_address');
$table->string('shelter_mobile_number');
$table->string('shelter_type');
});
}
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->foreignId('current_team_id')->nullable();
$table->string('profile_photo_path', 2048)->nullable();
$table->timestamps();
});
}
错误:
照亮 \ 数据库 \ QueryException
SQLSTATE[HY000]:常规错误:1364 字段“id”没有默认值
插入到数据库中
public function store(Request $request)
{
$Animal_shelter = new Animalshelter();
$Animal_shelter->shelter_name = $request->input('shelter_name');
$Animal_shelter->shelter_address = $request->input('shelter_address');
$Animal_shelter->shelter_mobile_number = $request->input('shelter_mobile_number');
$Animal_shelter->shelter_type = $request->input('shelter_type');
$Animal_shelter->save();
return redirect()->back()->with('status', 'shelter added successfully');
}
答:
0赞
Alexandru Ungureanu
6/14/2022
#1
不,它不会自动添加它。添加到庇护所表时,必须将 foreignid 设置为创建它的用户的用户 ID。
评论
0赞
vishwajeetpanwar
6/14/2022
嗨,我已经添加了用于将数据插入数据库的代码,我正在使用一个简单的代码,用户可以在没有任何角色和东西的情况下更新详细信息,为什么我需要拥有他们的 ID 才能掌握巨魔我想我需要使用会话来添加我不确定的密钥
0赞
Localhousee
6/14/2022
#2
这只是因为你没有设置字段。只需将其添加到您的对象中,然后就可以解决问题user_id
save()
$Animal_shelter->user_id = auth()->id() // In case you need to get authenticated user id
或者只是更改您的避难所迁移文件,使该列接受 null 值
$table->foreignId('user_id')->nullable()->constrained();
或者最后一个解决方案,如果你在雄辩的层面上建立用户和 Shelter 之间的关系,你可以链接功能,像这样
auth()->user()->shelters()->create(['your data']);
评论
id
id
user_id
id
users