简体   繁体   English

许多关系拉拉维拉

[英]Many Many Relationship laravel

I have 3 tables. 我有3张桌子。

  1. posts 帖子
  2. categories 类别
  3. category_post. category_post。

I want to add category_id and post_id in my category_post table when make a post with categories. 我想在列出类别的帖子时在category_post表中添加category_id和post_id。 I have checkbox for categories. 我有类别的复选框。

Main theme is, I want to create post with multiple categories. 主题是,我想创建具有多个类别的帖子。 So i want to add category_id and post_id in category_post table. 所以我想在category_post表中添加category_id和post_id。

is it possible with laravel??? 是否有可能与laravel ???

I have seen many tutorial and now i am tired. 我见过很多教程,现在我累了。 Please help me. 请帮我。

Please see the code below. 请参阅下面的代码。

My migrations tables: 我的迁移表:

<?php
 use Illuminate\Database\Migrations\Migration;
 use Illuminate\Database\Schema\Blueprint;

 class CreateCategoriesTable extends Migration {

/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::create('categories', function(Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('category_slug');
        $table->timestamps();
    });
}


     public function up()
{
    Schema::create('posts', function(Blueprint $table) {
        $table->increments('id');
        $table->string('title');
        $table->string('slug');
        $table->string('meta');
        $table->text('body');
        $table->string('image');
        $table->timestamps();
    });
}
    public function up()
{
    Schema::create('category_post', function(Blueprint $table) {
        $table->increments('id');
        $table->integer('category_id')->unsigned()->index();
        $table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
        $table->integer('post_id')->unsigned()->index();
        $table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
    });
}


/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::drop('categories');
}

    public function down()
{
    Schema::drop('posts');
}

    public function down()
{
    Schema::drop('category_post');
}
  } 

My post Controller: 我的帖子控制器:

<?php

  class PostsController extends \BaseController {

/**
 * Display a listing of posts
 *
 * @return Response
 */
public function index()
{
    $posts = Post::all();

    return View::make('admin.posts.index', compact('posts'));
}

/**
 * Show the form for creating a new post
 *
 * @return Response
 */
public function create()
{
    $categories = Category::all();


    return View::make('admin.posts.create',compact('categories'));
}

/**
 * Store a newly created post in storage.
 *
 * @return Response
 */
public function store()
{
    $validator = Validator::make($data = Input::all(), Post::$rules);

    if ($validator->fails())
    {
        return Redirect::back()->withErrors($validator)->withInput();
    }

    Post::create($data);

    return Redirect::route('admin.posts.index');
}

/**
 * Display the specified post.
 *
 * @param  int  $id
 * @return Response
 */
public function show($id)
{
    $post = Post::findOrFail($id);

    return View::make('admin.posts.show', compact('post'));
}

/**
 * Show the form for editing the specified post.
 *
 * @param  int  $id
 * @return Response
 */
public function edit($id)
{
    $post = Post::find($id);

    return View::make('admin.posts.edit', compact('post'));
}

/**
 * Update the specified resource in storage.
 *
 * @param  int  $id
 * @return Response
 */
public function update($id)
{
    $post = Post::findOrFail($id);

    $validator = Validator::make($data = Input::all(), Post::$rules);

    if ($validator->fails())
    {
        return Redirect::back()->withErrors($validator)->withInput();
    }

    $post->update($data);

    return Redirect::route('admin.posts.index');
}

/**
 * Remove the specified resource from storage.
 *
 * @param  int  $id
 * @return Response
 */
public function destroy($id)
{
    Post::destroy($id);

    return Redirect::route('admin.posts.index');
}

   }

My Post Model: 我的帖子模型:

 <?php

  class Post extends \Eloquent {

// Add your validation rules here
public static $rules = [
    'title'=>'required|min:2',
    'image'=>'required|image|mimes',
    'body' =>'required'
];

// Don't forget to fill this array
protected $fillable = ['title','meta','slug','image','body'];

public function categories()
{
    return $this->belongsToMany('Category');
}

}

My Category Controller: 我的类别控制器:

<?php

 class CategoriesController extends \BaseController {

public function __construct()
{
    $this->beforeFilter('csrf',['on'=>'post']);
}

/**
 * Display a listing of categories
 *
 * @return Response
 */
public function index()
{
    $categories = Category::all();

    return View::make('admin.categories.index', compact('categories'));
}

/**
 * Show the form for creating a new category
 *
 * @return Response
 */
public function create()
{
    return View::make('admin.categories.create');
}

/**
 * Store a newly created category in storage.
 *
 * @return Response
 */
public function store()
{
    $validator = Validator::make($data = Input::all(), Category::$rules);

    if ($validator->fails())
    {
        return Redirect::back()->withErrors($validator)->withInput();
    }

    Category::create($data);

    return Redirect::route('admin.categories.index');
}

/**
 * Display the specified category.
 *
 * @param  int  $id
 * @return Response
 */
public function show($id)
{
    $category = Category::findOrFail($id);

    return View::make('admin.categories.show', compact('category'));
}

/**
 * Show the form for editing the specified category.
 *
 * @param  int  $id
 * @return Response
 */
public function edit($id)
{
    $category = Category::find($id);

    return View::make('admin.categories.edit', compact('category'));
}

/**
 * Update the specified resource in storage.
 *
 * @param  int  $id
 * @return Response
 */
public function update($id)
{
    $category = Category::findOrFail($id);

    $validator = Validator::make($data = Input::all(), Category::$rules);

    if ($validator->fails())
    {
        return Redirect::back()->withErrors($validator)->withInput();
    }

    $category->update($data);

    return Redirect::route('admin.categories.index');
}

/**
 * Remove the specified resource from storage.
 *
 * @param  int  $id
 * @return Response
 */
public function destroy($id)
{
    Category::destroy($id);

    return Redirect::route('admin.categories.index');
}

    }

My Category Model: 我的分类型号:

  <?php

  class Category extends \Eloquent {
protected $fillable = ['name','category_slug'];

public static $rules = ['name'=>'required|min:3','category_slug'=>'required|min:3'];

public function posts()
{
    return $this->belongsToMany('Post');
}
}

My Create Post View: 我的创建帖子视图:

@extends('admin.layouts.main')

@section('content')
<h2>Create Post</h2>

@if ($errors->has())
    <div class="error">
        <p>The Following errors have</p>

        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif

{{ Form::open(array('action' => 'PostsController@store')) }}

<p>
    {{ Form::label('title') }}
    {{ Form::text('title') }}
</p>
<p>
    {{ Form::label('meta') }}
    {{ Form::text('meta') }}
</p>
<p>
    {{ Form::label('slug') }}
    {{ Form::text('slug') }}
</p>
<p>
    {{ Form::label('body') }}
    {{ Form::text('body') }}
</p>
<p>
    @foreach ($categories as $category)
        {{ Form::checkbox('category_id', $category->id) }}
        {{ Form::label($category->name) }}
    @endforeach
</p>
<p>
    {{ Form::label('image') }}
    {{ Form::text('image') }}
</p>

{{ Form::submit('Crate Post') }}
{{ Form::close() }}

 @stop

My Route: 我的路线:

<?php

 /*
|--------------------------------------------------------------------------
| Application Routes 
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the Closure to execute when that URI is requested.
|
*/

Route::get('/', function()
{
return View::make('hello');
 });

 Route::resource('admin/categories', 'CategoriesController');

 Route::resource('admin/posts', 'PostsController');

Please help me. 请帮我。 How do i add category_id and post_id in categoy_post table ???????? 如何在categoy_post表中添加category_id和post_id ????????

First you need an array of categories' ids: 首先,您需要一组类别ID:

// view
@foreach ($categories as $category)
    {{ Form::checkbox('categories[]', $category->id, $post->categories->contains($category->id)) }}
    {{ Form::label($category->name) }}
@endforeach

If you use model binding when editing, then rename categories[] to something else to avoid field name conflict 如果在编辑时使用模型绑定,则将categories[]重命名为其他内容以避免字段名称冲突

Then you need to sync the post with those categories: 然后,您需要将帖子与这些类别同步:

// posts controller @store

... // validate everything, categories too

$categories = Input::get('categories');

$post = Post::create($data);

$post->categories()->sync($categories);

return Redirect::route('admin.posts.index');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM