首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >落叶刀4插入枢轴台

落叶刀4插入枢轴台
EN

Stack Overflow用户
提问于 2014-03-25 02:41:13
回答 1查看 507关注 0票数 0

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

部门表属于许多类别,与类别相同,因此我有以下模型

代码语言:javascript
复制
 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');
}

 }

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

代码语言:javascript
复制
  $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提供了先进的帮助。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-03-25 11:42:21

首先,您应该将模型类命名为单数:类别、部门。

然后尝试使用透视表名声明您的关系:

代码语言:javascript
复制
public function categories()
{
    return $this->belongsToMany('Category', 'category_department');
}

代码语言:javascript
复制
public function departments()
{
    return $this->belongsToMany('Departments', 'category_department');
}

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

代码语言:javascript
复制
$findDepartment = Department::find($deptId);

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

$saveCat = $findDepartment->categories()->attach($category->id);
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22624504

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档