我正在努力在数据库中添加常见问题,使用Laravel5.6,许多到许多关系。以下是我的迁徙:
常见问题类别:(常见问题的所有类型列表)
Schema::create('faq_categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->softDeletes();
$table->timestamps();
});常见问题表:
Schema::create('faqs', function (Blueprint $table) {
$table->increments('id');
$table->string('title', 160);
$table->longText('description');
$table->boolean('published')->default(0);
$table->softDeletes();
$table->timestamps();
});常见问题类型:(特定常见问题的所有常见问题类别)
Schema::create('faq_types', function (Blueprint $table) {
$table->increments('id');
$table->integer('faq_id')->unsigned();
$table->foreign('faq_id')->references('id')->on('faqs')->onDelete('cascade');
$table->integer('faq_category_id')->unsigned();
$table->foreign('faq_category_id')->references('id')->on('faq_categories')->onDelete('cascade');
$table->timestamps();
});我定义了这样的关系:
App\FaqCategory
class FaqCategory extends Model {
use SoftDeletes;
public function faqs() {
return $this->belongsToMany('App\Faq');
}
}App\Faq
class Faq extends Model {
use SoftDeletes;
public function categories() {
return $this->belongsToMany('App\FaqCategory');
}
}我要所有的常见问题按他们的类别。假设General,Other类别在faq_categories表中,那么我想要按General,Other分组的常见问题。
但我无法检索所有按类别分组的常见问题。我做了以下工作,但面临错误:
$faq = FaqCategory::find(1);
return $faq->faqs;
dd($faq);错误:
SQLSTATE42S02:基本表或视图找不到: 1146表'db_name.faq_faq_category‘不存在。
有人能建议我如何处理这种情况或处理这件事的最佳方法吗?
发布于 2020-02-26 10:50:25
我认为你需要把你的关系定义为
public function faqs() {
return $this->belongsToMany('App\Faq', 'faq_types');
}和
public function categories() {
return $this->belongsToMany('App\FaqCategory', 'faq_types');
}因为你没有遵守惯例。
在默认情况下,Laravel查找表'faq_faq_category‘(按字母顺序排列的单数模型名称)。
您可以阅读更多有关定义多到多个关系( 在文件中 )的内容。
https://stackoverflow.com/questions/60412026
复制相似问题