laravel 4插入中的枢轴表

时间:2014-03-25 02:41:13

标签: laravel-4 pivot eloquent

嘿伙计们我是laravel的新人,我试图插入我的数据透视表。我在我的数据库中有这个结构

enter image description here

部门表属于许多类别,与类别相同,所以我有这个模型

 use Illuminate\Auth\UserInterface;
 use Illuminate\Auth\Reminders\RemindableInterface;

 class Departments extends Eloquent {

/**
 * The database table used by the model.
 *
 * @var string
 */
protected $table = 'departments';

protected $fillable = ['department_name'];

public $timestamps = false;

/**
 * The attributes excluded from the 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 {

/**
 * The database table used by the model.
 *
 * @var string
 */
protected $table = 'categories';

protected $fillable = ['name'];

public $timestamps = false;

/**
 * The attributes excluded from the model's JSON form.
 *
 * @var array
 */

public function department()
{
    return $this->belongsToMany('Departments');
}

 }

然后我在我的控制器中有这样的查询

  $messages = array(
        'required' => 'Please Fill the required field',
        'unique'    => 'Name Already 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));

} 

但是当我检查表格时,它会在类别表格中添加,但在category_department中没有添加任何内容。我想念任何代码吗?并且我上次尝试迁移我的数据透视表时出错了错误就是这个。

enter image description here

你可以帮助我解决我所缺少的问题吗? tnx提供高级帮助。

1 个答案:

答案 0 :(得分:2)

首先,您应该将模型类命名为单数:Category,Department。

然后尝试声明与数据透视表名称的关系:

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

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

现在,要插入新数据,请尝试附加:

$findDepartment = Department::find($deptId);

$category = Category::where('name', '=', $catName)->first();

$saveCat = $findDepartment->categories()->attach($category->id);