如何在laravel中插入多类别和多列不同类别的帖子?

时间:2016-08-03 14:35:17

标签: laravel laravel-5 laravel-5.2

大家好,我是一个新的laravel,我的项目有问题。我有2张桌子:

posts: id title category_id
category: id name(PHP, Laravel, Ruby)

例如:我想要结果,如果我在帖子中插入帖子数据库title = Jonh和chosse两个类别名称(PHP,Laravel),结果会有两列如post(id = 1 title(jonh)category_id (1),id = 2 title(jonh)category_id(2))但它仍然不起作用我尝试在google和youtube中找到并且它不起作用,这是我的代码:

View(create.blade.php)
{!!Form::open(array('route' => 'store', 'method' => 'POST'))!!}

{{Form::text('title')}}<br>

@foreach($category as $categories)
{{Form::label('category',$categories->name)}}
{{Form::checkbox('category_id', $categories->id) }}
@endforeach
<br>
{{Form::submit('submit')}}
{!!Form::close()!!}

Controller(PostsController.php)
public function create()
    {
        $category = Category::all();
        return view('create',compact('category'));
    }
    public function store(Request $request)
    {
       $post = new Posts;
       $post->title = $request['title'];
       $post->category_id = $request['category_id'];
       $post->save();
    }

帮助

1 个答案:

答案 0 :(得分:2)

您与帖子和类别之间的关系不正确。一个帖子应该有一个或多个类别,一个类别应该与零个或多个帖子相关联。

发布了多个类别
类别有多个帖子

下面我们有表结构:

-----帖子-----
id INT
title VARCHAR(100)
正文TEXT

----- category_post -----
category_id INT
post_id INT

-----类别-----
id INT
名称VARCHAR(100)

你应该做的是:

1 - 创建到category_post表的新迁移

<?php

// migrations/****_**_**_******_create_posts_table.php
Schema::create('posts', function(Blueprint $table) {
    $table->increments('id');
    $table->string('title', 100);
    $table->text('body');
});

// migrations/****_**_**_******_create_categories_table.php
Schema::create('categories', function(Blueprint $table) {
    $table->increments('id');
    $table->string('name', 100);
});

// migrations/****_**_**_******_create_category_post_table.php
Schema::create('category_post', function(Blueprint $table) {
    $table->integer('category_id')->unsigned();
    $table->integer('post_id')->unsigned();
    $table->foreign('category_id')->references('id')->on('categories')->onUpdate('cascade')->onDelete('cascade');
    $table->foreign('post_id')->references('id')->on('posts')->onUpdate('cascade')->onDelete('cascade');
});

2 - 更改您的Eloquent模型中的帖子和类别之间的关系。

<?php

// Post.php
public function categories()
{
    return $this->hasMany(Category::class);
}

// Category.php
public function posts()
{
    return $this->hasMany(Post::class);
}

现在你可以这样做:

// PostController.php
public function create()
{
    $categories = Category::all();

    return view('posts.create', compact('categories'));
}

public function store(Request $request)
{
    $post = new Post();
    $post->title = $request->name;
    $post->body = $request->body;
    $post->categories()->attach($request->categories_id);

    return redirect()->route('posts.index');
}

// views/posts/create.blade.php
<select name="categories_id" multiple>
@foreach ($categories as $category)
  <option value="{{ $category->id }}">{{ $category->name }}</option>
@endforeach
</select>