我正在学习Laravel中的存储库设计模式,我正在使用https://github.com/andersao/l5-repository
我认为我的项目取得了成功。但是当我使用存储库运行代码时,出现了一些问题
SQLSTATE[42S02]:找不到基表或视图:1146表"test.nhanviens"不存在(SQL:从
nhanviens
中选择*)
我的数据库中的表是Nhanvien而不是Nhanviens
在我的代码中
NhanvienPository.php
<?php
namespace App'Repositories;
use Prettus'Repository'Contracts'RepositoryInterface;
/**
* Interface NhanvienRepository
* @package namespace App'Repositories;
*/
interface NhanvienRepository extends RepositoryInterface
{
//
}
NhanvienPositoryEloquent.php
<?php
namespace App'Repositories;
use Prettus'Repository'Eloquent'BaseRepository;
use Prettus'Repository'Criteria'RequestCriteria;
use App'Repositories'NhanvienRepository;
use App'Entities'Nhanvien;
use App'Validators'NhanvienValidator;
/**
* Class NhanvienRepositoryEloquent
* @package namespace App'Repositories;
*/
class NhanvienRepositoryEloquent extends BaseRepository implements NhanvienRepository
{
/**
* Specify Model class name
*
* @return string
*/
public function model()
{
return Nhanvien::class;
}
/**
* Boot up the repository, pushing criteria
*/
public function boot()
{
$this->pushCriteria(app(RequestCriteria::class));
}
}
DataController.php
<?php
namespace App'Http'Controllers;
use Illuminate'Http'Request;
use App'Http'Requests;
use App'nhanvien;
use App'Repositories'NhanvienRepository;
class DataController extends Controller
{
protected $repository;
public function __construct(NhanvienRepository $repository){
$this->repository = $repository;
}
public function DanhSach(){
var_dump($this->repository->all());
}
}
将此变量添加到类中:
protected $table = 'nhanvien';
说明:除非明确指定了其他名称,否则类的复数名称"snake case"将用作表名。因此,在这种情况下,Eloquent将假设nhanvien模型将记录存储在nhanviens表中。
正如官方Eloquent文档中所述,您需要在Model定义中专门设置表名。也就是说,在App''Nhanvien.php文件中设置以下内容:
<?php
namespace App;
use Illuminate'Database'Eloquent'Model;
class Nhanvien extends Model
{
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'Nhanvien';
}
或使用
protected $table = 'nhanvien';
相反,如果您的表名是完全小写的。
检查迁移文件,可能您正在使用Schema::table
,如下所示:
架构::table('table_name',function($table){//…});
如果要创建新表,必须使用Schema::create:
Schema::create('table_name', function ($table) {
// ... });
有关更多信息,请参阅Laravel迁移文档。
如果您正在使用Schema::create
,请提供迁移文件的内容。
在我的例子中,我通过执行命令消除了类似的错误
php artisan config:cache