Heim  >  Fragen und Antworten  >  Hauptteil

Laravel erstellt eine falsche Tabelle

Ich benötige einen Download-Verlauf für jeden Benutzer, der unser System nutzt (im Grunde ein System, mit dem Benutzer Social-Media-Beiträge herunterladen können). Ich habe ein „DownloadHistory“-Modell erstellt, das die Felder ID, timestamp, download_history und user_id enthält. Wenn ich einen Benutzer erstelle, sollte automatisch eine Instanz von DownloadHistory erstellt und die Benutzertabelle aktualisiert werden, damit das Feld download_history_id die neu erstellte DownloadHistory-ID enthält, wie in meinem RegisterController angezeigt:

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

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

Das Problem ist: Ich erhalte eine Fehlermeldung, die für mich keinen Sinn ergibt:

Der Grund dafür, dass es für mich keinen Sinn ergibt, ist, dass ich nie

download_history erstellt habe, aber ich habe download_history erstellt. Was ist das also? ? ? Mein DownloadHistory-Modell ist:

<?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);
    }
}

Meine Migration zum Erstellen der Tabelle ist:

<?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粉546257913P粉546257913173 Tage vor279

Antworte allen(2)Ich werde antworten

  • P粉021708275

    P粉0217082752024-04-01 20:50:00

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

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

    Antwort
    0
  • P粉068510991

    P粉0685109912024-04-01 14:32:36

    在 Laravel 中,表名称假定为复数。

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

    要修复此问题,请在模型中使用 $table 属性。

    protected $table = 'download_history';

    Antwort
    0
  • StornierenAntwort