我创建了三个表,即国家/地区表、国家事件表和国家/地区事件表。 我想知道的第一个问题,是否需要表的具体名称?
这是我创建表的方法: 第一个是国家/地区表:
Schema::create('country', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
第二个是国家事件表:
Schema::create('countryevents', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->string('description');
$table->string('start');
$table->string('end');
$table->string('type');
$table->timestamps();
});
最后一个是我的country_countryevents 表:
Schema::create('country_countryevents', function (Blueprint $table) {
$table->increments('id');
$table->integer('country_id')->unsigned();
$table->foreign('country_id')->references('id')->on('country')->onDelete('cascade');
$table->integer('country_events_id')->unsigned();
$table->foreign('country_events_id')->references('id')->on('countryevents')->onDelete('cascade');
$table->integer('editable');
$table->timestamps();
});
我不确定我的代码发生了什么,因为我无法将事件附加到我的国家/地区。
Illuminate\Database\QueryException with message 'SQLSTATE[42S02]: Base table or view
not found: 1146 Table 'calendar.country_country__events' doesn't exist (SQL: insert into `cou
ntry_country__events` (`country__events_id`, `country_id`, `created_at`, `updated_at`) values
(1, 1, 2016-01-27 15:31:03, 2016-01-27 15:31:03))'
这是我运行 php artisantinker 并想要连接它们时的错误。
我确定我的模型是正确的,这是 Country.php 模型:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Country extends Model
{
//
protected $table='country';
public function country_events(){
return $this->belongsToMany('App\Country_Events')->withTimestamps();
}
}
这是我的 Country_Events.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Country_Events extends Model
{
protected $table='countryevents';
public function country(){
return $this->belongsToMany('App\Country')->withTimestamps();
}
}
谁能告诉我我的错误是什么?谢谢。
最佳答案
是的,您将需要引用表名称,可能还需要引用外键和本地键。
国家模式:
public function country_events(){
return $this->belongsToMany(
'App\Country_Events',
'country_countryevents',
'country_id',
'country_events_id'
)->withTimestamps();
}
Country_Events 模型:
public function country(){
return $this->belongsToMany(
'App\Country',
'country_countryevents',
'country_events_id',
'country_id'
)->withTimestamps();
}
关于php - Laravel 中的多对多关系需要表的特定名称吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35041649/