【问题标题】:How to create multiple models in Laravel 8 using single artisan command?如何使用单个工匠命令在 Laravel 8 中创建多个模型?
【发布时间】:2022-01-13 10:09:30
【问题描述】:

我正在努力使用 Laravel 8 中的 artisan 命令创建多个模型(我不想每次都运行命令来创建很多模型),但它给了我错误。

我尝试的是

php artisan make:model Photo Staff Product

我遇到的错误,

Too many arguments to "make:model" command, expected arguments "name".

【问题讨论】:

  • The docs 没有提到任何关于创建多个模型的内容,不知道您为什么认为这会起作用?你需要经常这样做吗?如果是,您可以编写一个简单的脚本。如果没有,只需为每个模型运行一次命令有什么问题吗?顺便说一句 - please do not post images of code/error messages.
  • 感谢您的建议。好吧,我自己试过了,没有任何描述可以一次创建多个模型。所以,我找到了 PowerShell 脚本并在这里分享。

标签: laravel-8 laravel-artisan laravel-models


【解决方案1】:

正如错误消息所示,它只需要一个参数,即您尝试创建的单一模型的名称。您不能在一个工匠命令中创建多个模型。

如果您的终端允许,向上键将使您返回上一个输入的命令,从而加快生成模型的过程。

【讨论】:

    【解决方案2】:

    我们可以使用 OS-native shell 来做到这一点。我们必须编写 PowerShell 执行此任务的脚本。

    来了,

    #checking if there is any artisan script present, if not then exit
    if (!(Test-Path ".\artisan" -PathType Leaf)) {
      echo "ERROR: Artisan not found in this directory"
      exit
    }
    
    #promting user
    $input = Read-Host -Prompt "Enter model names separated by commas"
    
    
    
    if (!$input) {
      echo "ERROR: No model names entered"
      exit
    }
    else
    {
        $input = $input -replace '\s',''       #removing white spaces if any           
        $input = $input -replace ',+',','      #removing more than 1 commas with single comma
    
        #checking if input contains any special character using regex
    
        if ( $input -match '[!@#\$%\^&\*\(\)\.\{\}\[\]\?\|\+\=\-\/]' ){
            echo "ERROR: Incorrect model names";
            exit
        }
    }
    
    echo "Enter switches to create additional classes (like -msfc)"
    $switch = Read-Host -Prompt "Enter the desired switches"
    
    if (!$switch) {
      echo "WARNING: No switch selected"
    } else {
      if ($switch -notmatch "-") {
        $switch = "-" + $switch
      }
      if ($switch -notmatch "[mscf]") {
        echo "ERROR: The switch can contain only [mscf] characters"
        exit
      }
    }
    
    $switch = $switch -replace '\s',''
    
    #spliting the string
    $models = $input.Split(",")
    
    foreach ($model in $models) {
      echo "Creating model $model"
      php artisan make:model $model $switch
    }
    

    使用以名称 artisan 开头的 .ps1 扩展名(例如 artisan-models.ps1)保存文件并使用 .\artisan-models.ps1 命令直接运行。 Here's Link

    【讨论】:

      猜你喜欢
      • 2017-08-28
      • 2015-05-24
      • 1970-01-01
      • 2015-07-09
      • 2015-04-13
      • 1970-01-01
      • 2013-03-18
      • 2014-08-30
      • 2020-03-02
      相关资源
      最近更新 更多