Laravel无法将数据存储到数据库

2cmtqfgy  于 2023-06-07  发布在  其他
关注(0)|答案(2)|浏览(177)

想要用laravel控制器将这些数据插入到数据库中,但没有错误消息,似乎数据不会被存储。
这是我的控制器功能

public function store3(){
        $time = new Time;
        $time->leaderboard_id = '1';
        $time->user_id = '1';
        $time->event_id = '1';
        $time->time = '1';
        $time->avg = '1';
        $time->save();
        return $this->scramble3(0);
    }

这是我的迁移表

Schema::create('time', function (Blueprint $table) {
            $table->id();
            $table->float("time");
            $table->unsignedBigInteger('leaderboard_id');
            $table->unsignedBigInteger('user_id');
            $table->unsignedBigInteger('events_id');
            $table->float('avg');
            $table->timestamps();
        });

        Schema::table('time', function (Blueprint $table) {
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade')->onUpdate("cascade");
            $table->foreign('leaderboard_id')->references('id')->on('leaderboards')->onDelete('cascade')->onUpdate("cascade");
            $table->foreign('events_id')->references('id')->on('events')->onDelete('cascade')->onUpdate("cascade");
        });
    }

我的型号代码

class Time extends Model
{
    use HasFactory;
    protected $table = "time";

    protected $fillable = [
        'id',
        'user_id',
        'leaderboard_id',
        'events_id',
        'time',
        'avg'
    ];

    public function User(){
        return $this->hasOne(User::class, 'User_id','id');
    }
    public function Leaderboard(){
        return $this->hasOne(Leadeboard::class, 'Leaderboard_id','id');
    }

    public function Event(){
        return $this->hasOne(Event::class, 'Events_id','id');
    }

    }

有什么问题吗?

brccelvz

brccelvz1#

试试这个

public function store3(){
    $time = new Time;
    $time->leaderboard_id = 1;
    $time->user_id = 1;
    $time->event_id = 1;
    $time->time = 1;
    $time->avg = 1;
    $time->save();
    return $this->scramble3(0);
}

您的模式是$table->unsignedBigInteger$table->float,但您将数据作为字符串$time->leaderboard_id = '1';传递

kzipqqlq

kzipqqlq2#

$time->event_id = '1';

应该是

$time->events_id = '1'; # 'event' <> 'events'

以后使用try{} catch{}进行调试

public function store3(){
    try {
        $time = new Time;
        $time->leaderboard_id = '1';
        $time->user_id = '1';
        $time->events_id = '1';
        $time->time = '1';
        $time->avg = '1';
        $time->save();

    } catch (\Exception $e) {
        dd($e->getMessage());
    }
    return $this->scramble3(0);
}

相关问题