当 运行 API 时流明查询异常

Lumen QueryException When Running API

我正在学习 Lumen Framework 并正在阅读该教程:Developing RESTful APIs with Lumen

目前正在工作,但是当我访问我的 api

http://example.com/api/accounts/2

它returns

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'youframe.accounts' doesn't exist (SQL: select * from accounts where accounts.id = 2 limit 1)

我有一个名为 Account.php

的模型文件
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Account extends Model
{
        protected $fillable = [
                'username', 'email', 'password', 'type' 
        ];

        protected $hidden = [];
}

和一个名为 AccountController.php

的控制器文件
<?php

namespace App\Http\Controllers;

use App\Account;
use Illuminate\Http\Request;

class AccountController extends Controller
{
        public function getAccount($id, Request $request)
        {
                $this->validate($request, [
                        'token' => 'required'           
                ]);

                return response()->json(Account::find($id), 400);
        }
}

我没有 table 叫 accounts。我唯一的 table 是 account,它从哪里调用 accounts?

将 table 名称添加到您的模型以将您的模型与后端数据库相关联 table。

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Account extends Model
{
        protected $fillable = [
                'username', 'email', 'password', 'type' 
        ];

        protected $hidden = [];
        protected $table = 'account';
}

如果您不提及 table 名称,Laravel 将采用您的型号名称的复数形式作为 table 名称。有关更多参考,请参阅 Eloquent Model Conventions

更新

如果您只想 select 某些列,请在 eloquent 查询中使用 select 命令。

$rows = Account::select(['column_name_1','column_name_2'])->get();

或者如果你想把它们放在一个数组中

$rows = Account::select(['column_name_1','column_name_2'])->get()->toArray();