Laravel雄辩的关系“一对多”,得到一个错误“SQLSTATE [42S02]:基表或视图未找到:1146”
问题描述:
根据以下代码 我试图创建“部分”和“旅游” 但我得到的错误 Table 'yourproject.sections' doesn't exist (SQL: select * from 'sections' where 'sections'.'id' = 1 limit 1)
我用迁移到创建表“部分”而不是“部分”Laravel雄辩的关系“一对多”,得到一个错误“SQLSTATE [42S02]:基表或视图未找到:1146”
注:如果我添加一个表名的模型我得到一个新的错误
Column not found: 1054 Unknown column 'tours.section_id' in 'where clause' (SQL: select * from `tours` where `tours`.`section_id` = 1)
我用m igrate以创建一个列 “sectionid” 而不是 “SECTION_ID”
型号 Section.php
<?php
class Section extends Eloquent{
protected $table = 'section';
protected $fullable = array('tit');
public function tours(){
return $this -> hasMany('Tours');
}
}
Tours.php
<?php
class tours extends Eloquent{
protected $fullable = array('tit','sectionid');
public function section(){
return $this -> belongsTo('Section');
}
}
迁移 科
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateSectionTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('section',function($table){
$table->increments('id');
$table->string('tit');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('section');
}
}
旅游
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateToursTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('tours',function($table){
$table->increments('id');
$table->string('tit');
$table->timestamps();
$table->integer('sectionid')->unsigned();
$table->foreign('sectionid')->references('id')->on('section');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('tours');
}
}
路线
<?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the Closure to execute when that URI is requested.
|
*/
Route::get('/', function()
{
$hotes = Section::find(1)->tours()->get();
return $hotes->tit;
});
答
因为你的外键列名不遵循Laravel的命名规则,你必须指定它:
public function tours(){
return $this->hasMany('Tours', 'sectionid');
}
而且
public function section(){
return $this->belongsTo('Section', 'sectionid');
}
我加在迁移文件中的外键'$表 - >整数( 'sectionid') - >无符号(); $ table-> foreign('sectionid') - >引用('id') - > on('section');' 并且还会在关系方法中添加'sectionid'并且仍然存在错误 – 2015-02-09 14:31:28
什么错误你得到了吗? – lukasgeiter 2015-02-09 14:33:17
SQLSTATE [42S02]:找不到基表或视图:1146'yourproject.sections'不存在(SQL:select * from'sections'其中'sections'.'id' = 1的限制1) – 2015-02-09 14:38:57