【问题标题】:Laravel migration target column value as default valueLaravel 迁移目标列值作为默认值
【发布时间】:2021-12-10 17:39:25
【问题描述】:

我有表articles 和这些列id, title, details, slug, 在我的 laravel 迁移默认值可以设置为:

$table->string('slug')->default('value');

有没有办法通过定位特定列来设置默认值?或者真的有可能吗?示例:我想将 slug 的默认值设置为列 id 的值; 所以如果我这样做了

Articles::create(['id' => 'uuid-1', 'title' => 'article 1', 'details' => 'details article 1']);

我希望该 slug 将 'uuid-1' 作为默认值,而在创建后不通过更新

【问题讨论】:

标签: laravel migration


【解决方案1】:

你可以类似地使用 Eloquent 创建方法。

<?php
    
    namespace App\Model;
    
    use Illuminate\Database\Eloquent\Model;
    use App\User;
    use Illuminate\Support\Str;
    
    class Articles extends Model
    {
        protected static function boot() {
            parent::boot();
    
            static::creating(function ($article) {
                $article->slug = Str::slug($article->id);
            });
        }
    
    //The rest of methods

【讨论】:

    【解决方案2】:

    显然,我认为这是不可能的。因为 laravel 在创建记录之前不可能知道它的 id。但即使这不是一个好的做法,我也可以为您提供一种方法。您可以将此代码添加到 Article 模型中,而不是在迁移中提供默认值:

        protected static function boot() {
            parent::boot(); // TODO: Change the autogenerated stub
    
            self::saving(function (Article $article){
                if ($article->getAttribute('slug') == null)
                {
                    $lastrecord = Article::latest()->first();
                    $slug = $lastrecord->id + 1;
               
                    $article->setAttribute('slug', $slug);
                }
            });
        }
    

    此代码将在创建每篇文章时起作用,并且在发送 slug 时不会执行任何操作。但是如果 slug 没有被发送,它将获取最新的记录,增加它的 id 并创建 slug 并自动注册它。所以你不需要任何更新过程。

    【讨论】:

      猜你喜欢
      • 2016-10-06
      • 2018-11-23
      • 2016-08-28
      • 2019-07-18
      • 2018-10-04
      • 1970-01-01
      • 2011-10-29
      • 1970-01-01
      • 2016-09-08
      相关资源
      最近更新 更多