简体   繁体   中英

Many to Many relation in Laravel5.4

I Want to Create multi category for posts in database but I Just create one category with this code: post.php

 public function Category()
{
    return $this->belongsTo('App\Category');
}

Category.php

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

posts_table:

 public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id');
        $table->integer('category_id');
        $table->string('title');
        $table->integer('price');
        $table->string('description');
        $table->timestamps();
    });
}

and view for create category is here:

   <form method="post" action="/storePost">
        {{csrf_field()}}
         <input type="hidden" id="user_id" name="user_id" value="
              {{Auth::user()->id}}">

      <lable>title</lable>
      <input type="text" id="title" name="title">

      <label>description</label>
      <input type="text" id="description" name="description">


      <label>price</label>
      <input type="text" name="price" id="price">

      <label>Category</label>
      <select name="category_id">
          @foreach($categories as $category)
          <option value={{$category->id}}>{{$category->name}}</option>
              @endforeach

      </select>


      <button type="submit" id="AddProduct">add</button>

  </form>

And my postcontroller to create category is:

  public function store()

  {

   Post::create([
       'user_id'=>request('user_id'),
       'title' => request('title'),
       'category_id'=>request('category_id'),
       'description'=>request('description'),
       'price'=>request('price'),
   ]);
   return redirect('/show');

}

How I Can create multi category for one posts in table?

You are going to need to design your database somewhat differently. You need a proper join table between the two tables. Your database should look something like this:

posts
  id
  //other

categories
  id
  //other

post_categories
  post_id
  category_id

Once you have the database setup with a proper join. You have to define the relations a little bit differently:

// App\Models\Post
public function categories() {
    return $this->belongsToMany('App\Category', 'post_categories', 'category_id', 'post_id');
}

// App\Models\Category
public function posts() {
    return $this->belongsToMany('App\Post', 'post_categories', 'post_id', 'category_id'); 
}

You can then use attach and detach to add and remove relations:

$post = Post::find(1);
$post->categories()->attach($categoryId);

You can read more about many-to-many relationships in the Laravel Documentation .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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