嘿,伙计们,我是新来的拉拉,我正试着把它插入我的枢轴桌子。我的数据库中有这个结构

部门表属于许多类别,与类别相同,因此我有以下模型
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中没有添加任何内容。我漏掉密码了吗?而且上一次我试图迁移枢轴表时出错了,错误是这样的。

你们能帮我弄清楚我错过了什么吗?tnx提供了先进的帮助。
发布于 2014-03-25 11:42:21
首先,您应该将模型类命名为单数:类别、部门。
然后尝试使用透视表名声明您的关系:
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);https://stackoverflow.com/questions/22624504
复制相似问题