我是Laravel 5.1的新手。我正在观看教程视频,而视频老师正在使用此代码在数据库中插入数据:
<?php
namespace App\Http\Controllers;
use App\comments;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class CommentController extends Controller
{
public function getCommentNew()
{
$data = array(
'commenter' => 'soheil' ,
'comment ' => 'Test content' ,
'email' => 'soheil@gmail.com' ,
'post_id' => 1 ,
) ;
comments::create( $data );
}
}
我正在做像他这样的步骤,但我遇到了问题,所有字段除created_at
和updated_at
都是空的,如下所示:
这是我的评论模型:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class comments extends Model
{
protected $fillable = ['commenter,email,post_id,comment,approved'];
public function post(){
return $this->belongsTo('App\posts');
}
}
这是迁移:
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCommentsTable extends Migration
{
public function up()
{
Schema::create('comments', function (Blueprint $table) {
$table->increments('id');
$table->unsignedinteger('post_id');
$table->string('commenter') ;
$table->string('email') ;
$table->text('comment') ;
$table->boolean('approved');
$table->timestamps();
});
}
public function down()
{
Schema::drop('comments');
}
}
答案 0 :(得分:5)
您尚未在模型中正确设置$fillable
属性,请尝试使用:
// in your model
protected $fillable = [
'commenter','email','post_id','comment','approved'
];
答案 1 :(得分:1)
您必须在可填充数组上单独定义列名称为上面答案中描述的shempignon 例如:['column1','column2'...] 不是一个字符串。每个列名称都必须是数组元素
答案 2 :(得分:1)
试试这个就没事了:),你忘记了protected $table = 'comments';
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class comments extends Model
{
protected $table = 'comments';
protected $fillable = ['commenter','email','post_id','comment','approved'];
public function post(){
return $this->belongsTo('App\posts');
}
}