我需要拥有将使用我们系统的每个用户的下载历史记录(基本上,是一个供用户下载社交媒体帖子的系统)。我创建了一个“DownloadHistory”模型,其中包含 ID、时间戳、download_history 和 user_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');
}
} Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
在模型中添加
protected $table = 'download_history';'array', ]; public function user() { return $this->belongsTo(User::class); } }在 Laravel 中,表名称假定为复数。
参考:https://laravel.com/docs/9.x /eloquent#表名
要修复此问题,请在模型中使用
$table属性。