根据以下代码
我尝试在“部分”和“旅行”之间建立关系
但我有错误
Table 'yourproject.sections' doesn't exist (SQL: select * from 'sections' where 'sections'.'id' = 1 limit 1)
 我使用迁移创建表“部分”而不是“部分”

注意:如果将表名称添加到模型中,则会出现新错误

Column not found: 1054 Unknown column 'tours.section_id' in 'where clause' (SQL: select * from `tours` where `tours`.`section_id` = 1)


我使用迁移创建列“ 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');
}

关于php - Laravel Eloquent 关系“一对多”,出现错误“SQLSTATE [42S02]:找不到基表或 View :1146”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28411507/

10-14 15:44
查看更多