保存到关系 table Laravel 4

Saving to relational table Laravel 4

基本上我有一个组 table 有 id 和名字,

我有另一个 table,带有 users_groups 和 id,group_id 和 user_id

我尝试在 users_groups table 中创建用户时进行保存,但是当我使用此代码时,它会在组 table 中保存它可以保存的内容。我做错了什么吗?

帐户控制器(将用户保存到数据库并将组设置为 id 1)

$user = User::create(array(
    'firstName' => $firstName,
    'lastName' => $lastName,
    'dateOfBirth' => $dateOfBirth,
    'gender' => $gender,
    'email' => $email,
    'username' => $username,
    'password' => Hash::make($password),
    'code' => $code,
    'active' => 0
));


Group::create([

    'user_id' => $user->id,
    'group_id' => '1' //1 is not assigned

]);

组模型

class Group extends Eloquent
{
    protected $fillable = array('name');

    // DEFINE RELATIONSHIPS --------------------------------------------------
    // define a many to many relationship
    // also call the linking table
    public function users() {
        return $this->belongsToMany('User', 'users_groups', 'group_id', 'user_id');
    }
}

用户模型

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

class User extends Eloquent implements UserInterface, RemindableInterface {

    protected $fillable =array('email', 'username', 'password', 'password_temp', 'code', 'active', 'firstName','lastName','gender','dateOfBirth');
    use UserTrait, RemindableTrait;

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

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = array('password', 'remember_token');

    // Each User BELONGS to many Groups
    // Define our pivot table also
    public function groups() {
        return $this->belongsToMany('Group', 'users_groups', 'user_id', 'group_id');
    }
}

保存关系的所有信息都可以找到here

你需要attach()

$user = User::create(array(
    'firstName' => $firstName,
    // ...
));

$user->groups()->attach(1); // 1 being the group_id