繁体   English   中英

Laravel行创建可填充

[英]Laravel row creation fillable

我需要为一个雄辩的模型中的每个新插入创建一个密钥(不可为空)。 该键不应放在$fillable数组中,因为根本不应该对其进行批量分配或更改。 我在模型中尝试过:

public static function boot()
{
    static::creating(function ($object) {
       $object->key = md5(uniqid("CT", true));
    });
}

但是它似乎不起作用,因为我得到一个例外的说法

SQLSTATE [23502]:不违反空值:7错误:“键”列中的空值...

您可以尝试在控制器中创建对象的新实例,然后手动分配所需的值,在nex示例中,我在批量分配之外指定票证的用户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();
}

你去

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([]);
=>  {
       id: "afedc2972f980d20ca95b556a93c0db1",
       updated_at: "2015-08-07 15:24:24",
       created_at: "2015-08-07 15:24:24"
   }
>>>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM