Laravel行创建可填写

时间:2015-08-07 14:49:17

标签: php laravel laravel-5

我需要为一个雄辩模型中的每个新插入创建一个键(不可为空)。此密钥不应位于$fillable数组中,因为它不应该被大量分配或更改。我在模型中试过这个:

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

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

  

SQLSTATE [23502]:非空违规:7 ERROR:'key'列中的空值...

2 个答案:

答案 0 :(得分:1)

您可以尝试在控制器中创建对象的新实例,然后手动确定所需的值,在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();
}

答案 1 :(得分:0)

你去了

mean型号

 Data %>%
      group_by(Species, IndID) %>%
      mutate(AvgPercent=mean(Percent))  %>%
      group_by(Species) %>% 
      arrange(desc(AvgPercent)) %>% 
      slice(1:4) %>% 
      select(-AvgPercent) %>%
      filter(!duplicated(IndID))
 #   IndID Species Season Percent
 #1     4     BHS Summer   0.996
 #2     1     BHS Summer   0.992
 #3    59     MTG Summer   0.956
 #4    63     MTG Summer   0.968

迁移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

进行测试
>>> $a = App\Test::create([]);
=>  {
       id: "afedc2972f980d20ca95b556a93c0db1",
       updated_at: "2015-08-07 15:24:24",
       created_at: "2015-08-07 15:24:24"
   }
>>>