【问题标题】:Saving to relational table Laravel 4保存到关系表 Laravel 4
【发布时间】:2015-02-01 12:44:51
【问题描述】:

基本上我有一个带有 id 和名称的组表,

我有另一个带有 id、group_id 和 user_id 的 users_groups 表

我尝试在将用户创建到 users_groups 表时保存,但是当我使用此代码时,它会在 groups 表中保存它可以保存的内容。是不是我做错了什么?

帐户控制器(将用户保存到数据库并将组设置为 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');
    }
}

【问题讨论】:

    标签: php mysql laravel relational-database


    【解决方案1】:

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

    你需要attach()

    $user = User::create(array(
        'firstName' => $firstName,
        // ...
    ));
    
    $user->groups()->attach(1); // 1 being the group_id
    

    【讨论】:

    • 我对其进行了修改,但出现错误.....调用非对象上的成员函数 save()
    • DB::table('users_groups') ->insert([ 'user_id' => $user->id, 'group_id' => '1' ]);
    • 做到了,它可以工作,但我猜这不是最好的方法......对不起,我对这个框架很陌生......第一次试用
    猜你喜欢
    • 2015-02-15
    • 1970-01-01
    • 2015-01-01
    • 1970-01-01
    • 2021-01-09
    • 2013-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多