我想创建一个博客,我有两个模型,Post和Tag。我想用透视表连接他们两个。这是一种多对多的关系,我无法弄清楚如何将帖子和标签链接在一起。当我尝试这样做时,它不会在我的数据库上返回任何内容。帖子有标题和内容,而标签只有名称。 我读过了,我必须使用同步方法或attach-detach,但我不知道该在哪里做。它是在帖子路线或标签路线?我已经通过利用包括职位和将它们分组在routes.php文件标签的路线:2个模型与数据透视表,多对多的关系
Route::resource('/tags', 'TagController');
Route::resource('/posts', 'PostController');
这是我到目前为止有:
我的Post模型:
class Post extends Model{
protected $fillable = [
'title', 'content'
];
protected $hidden = [
'view_count'
];
public function tags()
{
return $this->belongsToMany('App\Tag', 'post_tag');
}}
这里是我的标签型号:
class Tag extends Model{
protected $fillable = [
'name'
];
public function posts(){
return $this->belongsToMany('App\Post', 'post_tag');
}}
这里是我的post_tag透视表:
class CreatePostTagTable extends Migration{
public function up()
{
Schema::create('post_tag', function (Blueprint $table) {
$table->increments('id');
$table->integer('post_id')->unsigned()->nullable()->index();
$table->foreign('post_id')->references('id')->on('posts');
$table->integer('tag_id')->unsigned()->nullable()->index();
$table->foreign('tag_id')->references('id')->on('tags');
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('post_tag');
}}
代码看起来不错。你在尝试什么不起作用? –
当我想创建一篇文章时,我希望唯一的用户,即管理员,将他想要的任何标签与他的帖子关联起来。我应该使用sync方法创建什么路径来将帖子与标签连接起来,因为到目前为止,我的帖子和我的标签都是在创建时存储的,但是没有任何信息存储在post_tag表中 – livia
@joel hinz我现在意识到我的crud看起来不错,但我有一个与你无关的问题。我可以编辑洞问题以问我如何在帖子的创建视图中实现标签复选框? – livia