【问题标题】:Laravel unknown columnLaravel 未知列
【发布时间】:2017-11-05 14:15:55
【问题描述】:

我有这个错误的问题:

https://pastebin.com/cgm5yq0P

这是我的表格:

https://pastebin.com/bSU5X5EC

这是我的 web.php(路由控制器):

Route::post('/komentarz', 'VideosController@postComment');

这是我的 VideoController postComment 功能:

https://pastebin.com/SYbEjB8H

这是我的评论模型:

https://pastebin.com/SxHX6gTP

这是我的用户模型 cmets 函数:

    public function comments() {
    return $this->hasMany('App\Comment');
}

这是我的视频模型 cmets 函数:

public function comments(){ return $this->belongsToMany('App\Comment')->withTimestamps(); }

最后,名为 create_cmets_table 的迁移文件:

https://pastebin.com/2cHscQfq

我的路线: https://pastebin.com/ki8FZ0C6 请帮我解决这个问题。我不知道出了什么问题

【问题讨论】:

    标签: php sql laravel


    【解决方案1】:

    您的外键错误。将您的迁移更改为此。

    $table->unsignedInteger('user_id');
    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    
    $table->unsignedInteger('video_id');
    $table->foreign('video_id')->references('id')->on('videos')->onDelete('cascade');
    

    编辑:添加评论并将其附加到视频和用户。

    // model fillable property
    
    protected $fillable = [
        'text', 'user_id', 'video_id',
    ];
    
    // route
    Route::post('/film/{id}/komentarz', 'VideosController@postComment');
    
    // controller method
    public function postComment(CreateCommentRequest $request, $id)
    {
        $video = Video::findOrFail($id);
    
        $video->comments()->create([
            'text' => $request->text,
            'user_id' => auth()->id(),
        ]);
    
        return 'works';
    }
    
    // form
    {!! Form::open(['url' => "/film/{$video->id}/komentarz", 'method' => 'post','class' => 'form-horizontal']) !!}
    <div class="form-group">
        <div class="col-md-3 control-label">
            {!! Form::label('text', 'Treść komentarza:') !!}
        </div>
        <div class="col-md-8">
            {!! Form::textarea('text', null, ['class'=>'form-control', 'size' => '5x5']) !!}
        </div>
    </div>
    <div class="form-group">
        <div class="col-md-8 col-md-offset-3">
            {!! Form::submit('Dodaj', ['class'=>'btn btn-primary btn-comment']) !!}
        </div>
    </div>
    {!! Form::close() !!}
    

    【讨论】:

    • 工作,坦克很多:D
    • 但是你能告诉我如何获得这个视频的 cmets 吗?
    • @KurtCobain 添加 cmets 的方式是错误的。您没有将评论链接到视频。由于您有外键,因此评论应该失败。发布您的问题路线,我将向您展示如何在此基础上将 cmets 添加到视频中。
    • 我通过使用 $video->cmets 获得视频的 cmets?
    • @KurtCobain 是的
    【解决方案2】:

    在评论模型中,我看到“用户”是可填写的,而不是“用户 ID”。我认为应该是user_id。或者你可以使用

    protected guarded = [];
    

    而不是使用fillable 数组。

    【讨论】:

      猜你喜欢
      • 2015-04-01
      • 2015-02-22
      • 1970-01-01
      • 1970-01-01
      • 2020-05-13
      • 2018-12-16
      • 1970-01-01
      • 2016-04-29
      • 2021-08-08
      相关资源
      最近更新 更多