在自定义Laravel Artisan中使用模型

时间:2014-01-06 07:41:59

标签: php laravel laravel-4

编辑:添加了我的模型的命名空间部分。

我有一个工作的自定义Artisan命令,但是一旦我开始插入我创建的模型,我立刻就会遇到错误。

<?php namespace App\Command;

use App\Models\Samplemodel;

public function fire()
{
    $name = $this->argument('name');
    // This next line won't work
    $age = Samplemodel::get_age($this->option('bday')); // Line 42

    $this->line("My name is {$name} and my age is {$age}.");
}

我总是遇到错误:

{"error":{"type":"Symfony\\Component\\Debug\\Exception\\FatalErrorException","message":"Class 'App\\Models\\Samplemodel' not found","fi
le":"X:\\xampp\\htdocs\\laralabs\\laralabs.app\\app\\commands\\SampleCommand.php","line":42}}{"error":{"type":"Symfony\\Component\\De
bug\\Exception\\FatalErrorException","message":"Class 'App\\Models\\Samplemodel' not found","file":"X:\\xampp\\htdocs\\laralabs\\larala
bs.app\\app\\commands\\SampleCommand.php","line":42}}

我从此示例代码中删除了其他方法以保持清洁。基本上就是这样,这是否意味着我在创建自定义Artisan命令时无法使用模型?

根据要求,我的模型的前几行:

<?php namespace App\Models;

use DB;
use Config;
use Eloquent;
use DateTime;

class Helper extends Eloquent { ... }

我的模型的实际名称是Helper。该类没有任何属性方法。

1 个答案:

答案 0 :(得分:1)

它可以工作,只要你正确命名你的东西。我刚刚在这里测试了一下:

创建命令:

artisan command:make UseModel

将源代码更改为:

<?php

use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;

class UseModel extends Command {

    protected $name = 'model';

    protected $description = 'Command description.';

    public function __construct()
    {
        parent::__construct();
    }

    public function fire()
    {
        var_dump(ACR\Models\Article::all());
    }

    protected function getArguments()
    {
        return array(
        );
    }

    protected function getOptions()
    {
        return array(
        );
    }

}

将其添加到artisan.php:

Artisan::add(new UseModel);

然后跑去测试:

artisan model

它推翻了模型

这是模型:

<?php namespace ACR\Models;

class Article extends Eloquent {

    protected $table = 'articles';

}

也使用

工作
use ACR\Models\Article;

var_dump(Article::all());