如何在Laravel 5中通过artisan命令调用Model?

3

背景介绍:我是一个 Laravel 5 的新手,但我在过去的项目中使用过 Laravel 4。

在 Laravel 4 中,我只需在 Artisan 命令中直接调用模型即可。但现在,我该如何在 Artisan 命令中调用模型?以下是我的当前代码:

<?php 
   namespace App\Console\Commands;
   use Illuminate\Console\Command;
   use App\Models\sampleModel as sampleModel;

   class testCommand extends Command {

  /**
  * The console command name.
  *
  * @var string
  */
   protected $name = 'test';

  /**
  * The console command description.
  *
  * @var string
  */
   protected $description = 'Command description.';

   /**
   * Create a new command instance.
   *
   * @return void
   */
    public function __construct()
    {
        parent::__construct();
    }

   /**
   * Execute the console command.
   *
   * @return mixed
   */
    public function fire()
    {
        sampleModel::sampleMethod();
    }

}

以上是我的当前代码,但它给了我一个错误:[Symfony\Component\Debug\Exception\FatalErrorException] Class 'App\Models\DB' not found。 - Kugutsumen
我需要做的是在Artisan命令中调用模型的一个方法,并通过CLI执行它。 - Kugutsumen
1个回答

2

你的问题与命令无关,你可以在命令中使用 Model。

问题出现在你的 Model 中,请在 Model 开头添加以下内容:

use DB;

注意1:Laravel模型应该以首字母大写命名:SampleModel,而不是sampleModel
注意2:由于模型已经命名为sampleModel,因此as sampleModel是多余的。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接