2017-11-28 3 views
1

私はlaravelでphpを学んでいて、私のプロジェクトで複数のカテゴリとサブカテゴリを実装しようとしています。 例:私は自分のプロジェクトにBooks、Mobilesを持っています Booksには独自のカテゴリとサブカテゴリがあります。モバイルでも同じです私はdidnのような関係Laravelカテゴリ

Schema::create('category_product', function (Blueprint $table) { 
      $table->increments('id'); 
      $table->integer('product_id')->unsigned(); 
      $table->integer('category_id')->unsigned(); 
      $table->unique(array('product_id', 'category_id')); 

      // foreign key constraints are optional (but pretty useful, especially with cascade delete 
      $table->foreign('product_id')->references('id')->on('products')->onDelete('cascade'); 
      $table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade'); 
     }); 

カテゴリーデータベーススキーマ

Schema::create('categories', function (Blueprint $table) { 
     $table->increments('id'); 
     $table->integer('parent_id')->nullable()->index(); 
     $table->string('title')->unique(); 
     $table->string('slug')->unique(); 
     $table->string('description')->nullable(); 
     $table->string('keywords')->nullable(); 
     $table->timestamps(); 
    }); 

category.php(モデル)

<?php 

namespace App; 

use Illuminate\Database\Eloquent\Model; 
use Cviebrock\EloquentSluggable\Sluggable; 

class Category extends Model 
{ 
    use Sluggable; 
    /** 
    * Return the sluggable configuration array for this model. 
    * 
    * @return array 
    */ 
    public function sluggable() 
    { 
     return [ 
      'slug' => [ 
       'source' => 'title' 
      ] 
     ]; 
    } 
    /** 
    * The database table used by the model. 
    * 
    * @var string 
    */ 
    protected $table = 'categories'; 

    /** 
    * Attributes that should be mass-assignable. 
    * 
    * @var array 
    */ 
    protected $fillable = [ 
     'parent_id', 'title', 'description', 'slug' 
    ]; 

    public function parent() 
    { 
     return $this->belongsTo('Category', 'parent_id'); 
    } 

    public function children() 
    { 
     return $this->hasMany('Category', 'parent_id'); 
    } 

    public function categoryProduct(){ 
     return $this->belongsToMany('CategoryProduct'); 
    } 

    public function product(){ 
     return $this->belongsToMany('Product'); 
    } 
} 

私は正しい方法をやっていると、別のテーブルを追加した

この種のアプローチのための適切なチュートリアルを見つけることはできません。 CategoryProduct.phpモデルと参照を作成する必要がありますか

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

答えて

1

いいえ、ピボットテーブルのモデルを作成する必要はありません。 Eloquentには、ピボットテーブルを使った作業を簡単に行える多くの方法があります。あなたの場合、モデルは必要ありません。

しかし、ピボットテーブルの追加列を使用して作業する場合、ピボットテーブルのモデルを作成することをお勧めします。

+0

そして、私はクラスを宣言する必要がありますカテゴリはEloquentを延長します –

+0

@SrikanthGopi 'Category'クラスは' Model'を拡張する必要があります –

+1

私はそれを得ました。 Thanls @AlexeyMezenin –

関連する問題