gpt4 book ai didi

php - laravel 中的多对多关系需要表的特定名称吗?

转载 作者:行者123 更新时间:2023-11-29 01:37:50 25 4
gpt4 key购买 nike

我创建了三个表,分别是国家表、countryevents 表和 country_countryevents 表。我想知道的第一个问题是需要表的具体名称吗?

这是我创建表格的方式:第一个是国家表:

 Schema::create('country', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();

});

第二个是countryevents表:

 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 artisan tinker 并想连接它们时的错误。

我确定我的模型是正确的,这是 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com