SQLSTATE [42S02]:未找到基本表或视图(belongsToMany)Laravel 5.4
请有人帮我解决这个问题。我是laravel的新手,现在我需要将选择标记的数组存储到mysql,并且我有这个erorr。 SQLSTATE [42S02]:未找到基本表或视图:1146'cmsystem.account_code_project'不存在(SQL:从account_code_project
中选择account_code_ac_id
,其中project_pj_id
= 1)。似乎它与使用belongsToMany()函数有关。我应该在这里做什么是我的代码。SQLSTATE [42S02]:未找到基本表或视图(belongsToMany)Laravel 5.4
这里的project_table
//project table
Schema::create('projects', function(Blueprint $table)
{
$table->increments('pj_id');
$table->string('pj_title',100);
$table->string('pj_description');
});
这里的accountcodes表
//codes
Schema::create('accountcodes', function(Blueprint $table)
{
$table->increments('ac_id');
$table->string('ac_code',100)->nullable();
$table->string('ac_description')->nullable();
});
这里的中间表的两个表
//intermediate table
Schema::create('code_project', function(Blueprint $table){
$table->increments('id');
$table->integer('project_id')->unsigned();
$table->foreign('project_id')->references('pj_id')->on('projects');
$table->integer('account_id')->unsigned();
$table->foreign('account_id')->references('ac_id')->on('accountcodes');
});
项目控制器
//ProjectController
public function store(Request $request)
{
$this->validate($request,[
'pj_title'=>'required',
'pj_description'=>'required',
]);
$project = new project;
$project->pj_title = $request->pj_title;
$project->pj_description = $request->pj_description;
$project->save();
$project->accounts()->sync($request->accounts, false);
return redirect('/projectlist');
}
个
模型
//AccountCode
protected $table = 'accountcodes';
public function projects()
{
return $this->belongsToMany('App\Project');
}
//Project
protected $table = 'projects';
public function accounts()
{
return $this->belongsToMany('App\AccountCode');
}
谢谢。
可以在belongsToMany
return $this->belongsToMany('App\AccountCode',"code_project");
提示表名。这是因为按照惯例透视表应该被命名为:accountcode_project
(这也并不反映本应是型号名称Accountcode
)
这是因为你必须指定模型关系的透视表名:
return $this->belongsToMany('App\Project', 'code_project');
否则Eloquent会尝试按照其约定检测默认表名,我鼓励您遵循该约定。
我是否需要指定它在我的模型?我的意思是这样的 返回$ this-> belongsToMany('App \ Project','code_project'); return $ this-> belongsToMany('App \ AccountCode','code_project'); – kalawadei
是的好友 - https://laravel.com/docs/5.4/eloquent-relationships#many-to-many – xyzale
在belongsToMany标签中添加“code_project”不会改变任何东西,所以我做的是我将表名改为“ accountcode_project”。仍然错误仍然是一样的。我没有看到任何错误。我该怎么办?对不起,谢谢 – kalawadei
好吗我通过声明两个模型都代表,所以它看起来像这样
//AccountCode
public function projects()
{
return $this->belongsToMany('App\Project', 'accountcode_project', 'ac_id', 'pj_id');
}
// Project
public function accountcodes()
{
return $this->belongsToMany('App\AccountCode', 'accountcode_project', 'pj_id', 'ac_id');
}
我应该需要指定它在我的两个模型来解决呢?我的意思是这样的 返回$ this-> belongsToMany('App \ Project','code_project'); return $ this-> belongsToMany('App \ AccountCode','code_project'); – kalawadei
@ClaudeDizon是的,无论你需要使用该数据透视表。问题是你没有遵循命名约定。 – apokryfos
在belongsToMany标记中添加“code_project”不会改变任何内容,所以我所做的是将表名更改为“accountcode_project”。仍然错误仍然是一样的。我没有看到任何错误。我该怎么办?对不起,谢谢。 – kalawadei