pivot table in laravel 4 insertion -


hey guys im new in laravel , trying insert pivot table. have structure in database

enter image description here

the departments table belongs many categories , same category have models

 use illuminate\auth\userinterface;  use illuminate\auth\reminders\remindableinterface;   class departments extends eloquent {  /**  * database table used model.  *  * @var string  */ protected $table = 'departments';  protected $fillable = ['department_name'];  public $timestamps = false;  /**  * attributes excluded model's json form.  *  * @var array  */  public function categories()  {     return $this->belongstomany('categories');   }   }      use illuminate\auth\userinterface;    use illuminate\auth\reminders\remindableinterface;     class categories extends eloquent {  /**  * database table used model.  *  * @var string  */ protected $table = 'categories';  protected $fillable = ['name'];  public $timestamps = false;  /**  * attributes excluded model's json form.  *  * @var array  */  public function department() {     return $this->belongstomany('departments'); }   } 

then have query in controller this

  $messages = array(         'required' => 'please fill required field',         'unique'    => 'name exist'     );      $catname = input::get('categoryname');     $deptid = input::get('deptid');      $validation = validator::make(input::all(),[         'categoryname' => 'required|unique:categories,name' ], $messages);       if($validation->fails()){          return array('error' =>$validation->messages()->all() );     }else{          $finddepartment = departments::find($deptid);          $savecat = $finddepartment->categories()->insert(array('name' => $catname));  }  

but when checked tables adds on categories table nothing added in category_department. miss codes? , had error last time trying migrate pivot table error this.

enter image description here

can me guys on missing? tnx in advanced.

first, should name model classes singular: category, department.

then try declare relationships pivot table name:

public function categories() {     return $this->belongstomany('category', 'category_department'); } 

and

public function departments() {     return $this->belongstomany('departments', 'category_department'); } 

now, insert new data, try attach:

$finddepartment = department::find($deptid);  $category = category::where('name', '=', $catname)->first();  $savecat = $finddepartment->categories()->attach($category->id); 

Comments

Popular posts from this blog

user interface - How to replace the Python logo in a Tkinter-based Python GUI app? -

objective c - Greedy NSProgressIndicator Allocation -

how to set an OCR language in Google Drive -