【问题标题】:laravel 5.5 use model in commandlaravel 5.5 在命令中使用模型
【发布时间】:2017-11-07 19:32:49
【问题描述】:

我是 Laravel5.5 的新手,想在我的命令中使用模型,
首先 php artisan make:model MyTest,然后我使用模型从 mysql 获取数据。
命令文件:

<?php
namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Model\MyTest;

class UboxDataAnalysis extends Command
{
    //...

    public function handle()
    {
        $this->line('Then start query');
        $o = new App\Model\MyTest();
    }
}

模型文件是:

<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use DB;

class MyTest extends Model
{
    //
    function get_data(){
        $uboxTest = DB::connection('mysql-test');
        $res = $uboxTest::table('m_user')->where('user_id',166);
        var_dump($res);
    }
}

但是 CLI 输出是:

[Symfony\Component\Debug\Exception\FatalThrowableError]    
Class 'App\Console\Commands\App\Model\MyTest' not found

我用谷歌搜索了一些关于laravel5.5 doc的信息。
To get started, let's create an Eloquent model. Models typically live in the app directory, but you are free to place them anywhere that can be auto-loaded according to your composer.json file.
也就是说,我需要在 composer.json 中添加一些配置吗?
有人可以给我一些建议吗?思考。

【问题讨论】:

    标签: php laravel-5.5


    【解决方案1】:

    你已经用use App\Model\MyTest; 导入了类,所以你可以写$o = new MyTest();
    取而代之的是,您可以删除 import 语句并编写 $o = new \App\Model\MyTest();(注意添加的反斜杠)。

    【讨论】:

    • 哦,原来如此,我对namespace不是很了解,那我再去阅读php namespace的内容。
    猜你喜欢
    • 2018-12-28
    • 2018-07-11
    • 2018-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-13
    • 2019-04-03
    相关资源
    最近更新 更多