根据以下代码
我尝试在“部分”和“游览”之间建立关系
但我得到了错误
表“yourproject.sections”不存在(SQL:select * from 'sections' where 'sections'.'id' = 1 limit 1)
我使用 migrate 创建表“section”而不是“sections”
注意:如果我将表名添加到模型中,我会收到一个新错误
Column not found: 1054 Unknown column 'tours.section_id' in 'where clause' (SQL: select * from `tours` where `tours`.`section_id` = 1)
我使用 migrate 创建列“sectionid”而不是“section_id”
型号 部分.php
<?php
class Section extends Eloquent{
protected $table = 'section';
protected $fullable = array('tit');
public function tours(){
return $this -> hasMany('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');
}
关于php - Laravel Eloquent 关系 "one to many",出现错误 "SQLSTATE[42S02]: Base table or view not found: 1146",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28411507/