Laravel 建立錯誤的表
P粉546257913
P粉546257913 2024-03-31 23:23:45
0
2
283

我需要擁有將使用我們系統的每個用戶的下載歷史記錄(基本上,是一個供用戶下載社交媒體帖子的系統)。我建立了一個「DownloadHistory」模型,其中包含 ID時間戳download_historyuser_id 欄位。當我建立使用者時,應該自動建立DownloadHistory 的實例,並且使用者表會更新為具有欄位download_history_id 來包含新建立的DownloadHistory's id,如我的RegisterController 中所示:

$downloadHistory = DownloadHistory::create([
    'user_id' => $user->id
]);

DB::table('users')->where('id', $user->id)->update(['download_history_id' => $downloadHistory->id]);

問題是:我收到一個錯誤,這在我看來毫無意義:

它對我來說沒有意義的原因是,我從未創建過download_history,但我確實創建了download_history,所以這是什麼? ? ? 我的 DownloadHistory 模型是:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class DownloadHistory extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
    ];

    protected $casts = [
       'downloads' => 'array',
    ];

    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

我建立表格的遷移是:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateDownloadHistoryTable extends Migration
{  
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('download_history', function (Blueprint $table) {
            $table->id();                        
            $table->timestamps();
            $table->json('history');
            $table->integer('user_id');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('download_history');
    }
}

P粉546257913
P粉546257913

全部回覆(2)
P粉021708275

在模型中加入 protected $table = 'download_history';

#
 'array',
    ];

    public function user()
    {
        return $this->belongsTo(User::class);
    }
}
P粉068510991

在 Laravel 中,表名稱假定為複數。

參考:https://laravel.com/docs/9.x /eloquent#表名

要修正此問題,請在模型中使用 $table 屬性。

protected $table = 'download_history';
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!