如何使用自定义 artisan 命令从数据库中打印一行

how to print a row from the database using custom artisan command

我正在尝试使用 Laravel 中的自定义 artisan 命令从第二个数据库中获取一行。现在我想打印查询结果,但我一直收到错误消息。我将不胜感激任何帮助。

我设置了与两个数据库的连接,它们已连接并且运行没有问题。我正在使用的 table 称为 person,包含多个列,例如 name、surname、person_id(自动递增和主键)和 ssn .我还创建了一个自定义 artisan 命令,该命令在使用

时从数据库中获取一行

php artisan import-users:DB 12345678

和查询

DB::connection('mysql2')->select('SELECT * FROM person WHERE ssn=?', [$ssn])

查询结果放在变量 $user 中,现在我只想打印出来,但我不断收到错误。这是我试过的

$name = $user['name']; 

这给出了

ErrorException : Undefined index: name

$this->line($user[0]);

这给出了

ErrorException : Object of class stdClass could not be converted to string

$this->line($user->name);

这给了

ErrorException : Trying to get property 'name' of non-object

我也尝试了很多东西,但都没有用。再次感谢

<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use DB;

class ImportUsers extends Command{

    protected $signature = 'import-users:DB {ssn}';
    protected $description = 'import users from old database';

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

    public function handle()
    {
        $ssn = $this->argument('ssn');
        $user = DB::connection('mysql2')->select('SELECT * FROM person WHERE 
            ssn=?', [$ssn]);
        $this->line($user->name);
        $this->info($ssn.' Done');
    }
}

像那样使用

for signle row
public function handle()
        {
            $ssn = $this->argument('ssn');
            $user = DB::connection('mysql2')->select('SELECT * FROM person WHERE 
                ssn=? limit 1', [$ssn]);

            if(isset($user[0])){
                 $this->line($user[0]->name); 
            }
            $this->info($ssn.' Done');
            $this->table($headers, $newUsers);
      }

for multiple rows(array)

public function handle()
    {
        $ssn = $this->argument('ssn');
        $user = DB::connection('mysql2')->select('SELECT * FROM person WHERE 
            ssn=?', [$ssn]);
         //$userNameArray = [];  //if you want to show name in table 
         if(count($user) > 0) {
           foreach($user as $item)  {
              $this->line($item->name);
              //$userNameArray[] = $item->name;
            }
        } 

       $this->info($ssn.' Done');
       //$this->table(['Name'],$userNameArray); //optionall 
    }