我正在尝试创建一个包含laravel 5.7中的部分和类别的论坛。所有这些部分都有多个类别。
当我建立关系时,尝试在视图中获取数据,我得到一个错误:
SQLSTATE[42S22]: Column not found: 1054 Unknown column
'forum_categories.forum_section_id' in 'where clause' (SQL: select * from `forum_categories` where `forum_categories`.`forum_section_id` = 1 and `forum_categories`.`forum_section_id` is not null)
这是我的刀刃:
@foreach($sections as $section)
<h1 data-toggle="collapse" data-target="#section{{$section->id}}">{{$section->name}}</h1>
<div class="collapse" id="section{{$section->id}}">
Dit is sectie
@foreach($section->ForumCategory as $forumCategory)
{{$forumCategory->id}}
@endforeach
</div>
@endforeach
我的控制器功能index():
$sections = ForumSection::all();
return view('forum.index', compact(['sections']));
这是我的模特: 论坛类别
namespace App;
use Illuminate\Database\Eloquent\Model;
class ForumCategory extends Model
{
protected $fillable = [
'name', 'active', 'position', 'section_id'
];
public function ForumSection() {
return $this->belongsTo(ForumSection::class, 'section_id');
}
}
模型论坛部分:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class ForumSection extends Model
{
protected $fillable = [
'name','active', 'position'
];
public function ForumCategory() {
return $this->hasMany(ForumCategory::class, 'section_id');
}
}
最后:我的2个数据库表:
论坛部分表
public function up()
{
Schema::create('forum_sections', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->boolean('active');
$table->integer('position')->unique();
$table->timestamps();
});
}
论坛分类表
public function up()
{
Schema::create('forum_categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->integer('active');
$table->integer('section_id')->unsigned();
$table->timestamps();
});
Schema::table('forum_categories', function (Blueprint $table)
{
$table->foreign('section_id')->references('id')->on('forum_sections');
});
}
有人可以告诉我我做错了什么吗?
答案 0 :(得分:2)
这应该很清楚...它正在寻找
'forum_categories.forum_section_id'
作为链接ID,但您使用的是
Schema::create('forum_categories', function (Blueprint $table) {
...
$table->integer('section_id')->unsigned();
});
要解决此问题,您有两种选择:覆盖迁移并使用forum_section_id
而不是section_id
,或将ID添加到您的关系中:
return $this->hasMany(ForumCategory::class, 'section_id');
对于belongsTo
方法,您正确地做到了这一点,但是似乎在hasMany
(反方法)中错过了它。
接下来,使用循环获取单个id
,因为$seciton->ForumCategory
是Collection
,而不是单个Model:
@foreach($section->ForumCateogry AS $forumCateogry)
Dit is sectie {{ $forumCateogry->id }}
@endforeach
这带来了有关命名约定的注释;方法名称通常是“ camelCase”,因此forumCateogry()
而不是ForumCateogry()
,并且对于返回多个值的方法,它是复数的,所以forumCateogries()
而不是forumCateogry()
答案 1 :(得分:0)
解决方案很简单...我将ForumCategory和ForumSection重命名为Category和Section,问题就消失了。。。我学到了一个教训;)