【问题标题】:Laravel row creation fillableLaravel 行创建可填充
【发布时间】:2015-08-07 14:49:16
【问题描述】:
我需要为雄辩模型中的每个新插入创建一个密钥(不可为空)。这个键不应该在$fillable 数组中,因为它根本不应该被大量分配或更改。我在模型中试过这个:
public static function boot()
{
static::creating(function ($object) {
$object->key = md5(uniqid("CT", true));
});
}
但它似乎不起作用,因为我得到一个异常说
SQLSTATE[23502]:非空违规:7 错误:“键”列中的空值...
【问题讨论】:
标签:
php
laravel
laravel-5
【解决方案1】:
您可以尝试在控制器中创建对象的新实例,然后手动分配您需要的值,在下一个示例中,我在批量分配之外指定票证的用户 ID
我使用的模型是这样的
class TicketComment extends Entity
{
protected $fillable = ['comment', 'link'];
/**
* Return the ticket of the given comment.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function ticket()
{
return $this->belongsTo(Ticket::getClass());
}
/**
* Return the user of the given comment.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function user()
{
return $this->belongsTo(User::getClass());
}
}
这是保存评论的方法,注意我是如何添加用户ID的
public function submit($id, Request $request, Guard $auth)
{
$this->validate($request, [
'comment' => 'required|max:250',
'link' => 'url'
]);
$comment = new TicketComment($request->all());
$comment->user_id = $auth->id();
$ticket = Ticket::findOrFail($id);
$ticket->comments()->save($comment);
session()->flash('success', 'Your comment has been saved successfully');
return redirect()->back();
}
【解决方案2】:
你来了
App\Test.php型号
namespace App;
use Illuminate\Database\Eloquent\Model;
class Test extends Model
{
protected $table = 'test';
protected $primaryKey = 'id';
protected $fillable = [];
public $incrementing = false;
public function getNewId()
{
return md5(uniqid("CT", true));
}
protected static function boot()
{
parent::boot();
static::creating(function ($model) {
$model->{$model->getKeyName()} = $model->getNewId();
});
}
}
test 表的迁移
class CreateTestTable extends Migration
{
public function up()
{
Schema::create('test', function (Blueprint $table) {
$table->string('id');
$table->timestamps();
$table->primary('id');
});
}
public function down()
{
Schema::drop('test');
}
}
让我们用tinker测试一下
>>> $a = App\Test::create([]);
=> {
编号:“afedc2972f980d20ca95b556a93c0db1”,
更新时间:“2015-08-07 15:24:24”,
created_at:“2015-08-07 15:24:24”
}
>>>