[英]Many to Many relation in Laravel5.4
我想為數據庫中的帖子創建多個類別,但是我只使用以下代碼創建一個類別: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();
});
}
並在此處查看創建類別的視圖:
<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>
我創建類別的后控制器是:
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');
}
如何為表格中的一個帖子創建多類別?
您將需要對數據庫進行一些不同的設計。 您需要在兩個表之間使用適當的聯接表。 您的數據庫應如下所示:
posts
id
//other
categories
id
//other
post_categories
post_id
category_id
一旦使用正確的聯接進行數據庫設置。 您必須對關系進行一些不同的定義:
// 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');
}
然后,您可以使用attach
和detach
來添加和刪除關系:
$post = Post::find(1);
$post->categories()->attach($categoryId);
您可以在Laravel文檔中閱讀有關多對多關系的更多信息 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.