是的,所以我有一個帶有用戶 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();
});
}
錯誤 :
照亮\資料庫\查詢例外
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');
}
uj5u.com熱心網友回復:
只是因為你沒有設定user_id欄位。只需將其添加到您的物件中即可save()解決問題
$Animal_shelter->user_id = auth()->id() // In case you need to get authenticated user id
或者只是更改您的避難所遷移檔案,以便該列接受空值
$table->foreignId('user_id')->nullable()->constrained();
或者最后一個解決方案,如果你在 eloquent 級別上設定 User 和 Shelter 之間的關系,你可以鏈接函式,像這樣
auth()->user()->shelters()->create(['your data']);
第二個解決方案 第三個解決方案
uj5u.com熱心網友回復:
不,它不會自動添加它。當您添加到庇護表時,您必須將 foreignid 設定為創建它的用戶的用戶 ID。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/490517.html
