【发布时间】:2019-12-27 22:38:32
【问题描述】:
我正在通过开发一个小型博客来学习 Laravel,以了解该框架及其提供的功能。我现在面临的问题是“如何检索帖子最初所属类别的名称”
我的帖子和类别之间的关系是多对多的。 我有三张桌子
Post
Category
CategoryPost
我的帖子模型
public function categories()
{
return $this->belongsToMany('App\category');
}
我的分类模型
public function posts()
{
return $this->belongsToMany('App\Post');
}
除此之外,我还没有制作任何数据透视表模型。 我需要做吗?
我的数据透视表中的记录如下:
id category_id post_id
------ ----------- ---------
6 1 16
7 2 16
8 3 16
9 1 17
10 3 17
11 1 18
12 2 18
我想显示一个帖子最初所属的当前类别的名称,以便用户可以在编辑页面中添加或删除类别。
这些是我的迁移:
张贴表
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id');
$table->Integer('status_id');
$table->string('title');
$table->text('body');
$table->text('media');
$table->string('tags');
$table->timestamps();
});
}
分类表:
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->text('description');
$table->timestamps();
});
}
CategoryPost 表:
public function up()
{
Schema::create('category_post', function (Blueprint $table) {
$table->increments('id');
$table->integer('category_id');
$table->integer('post_id');
$table->timestamps();
});
}
【问题讨论】:
-
您能提供您在控制器中尝试过的内容吗?
-
公共函数编辑(Post $post) { $post=Post::find($post->id); $categories=类别::all(); return view('admin.pages.post.edit',compact('post','categories')); }
-
这是我目前在后期控制器的编辑方法中尝试过的
标签: php laravel eloquent blogs