我有用户,用户属于经销商.

在用户注册后,我试图保存一个新用户和一个新经销商.

用户数据库有一个dealership_id列,我想用新创建的经销商的ID填充该列.

This is my current code in the UserController store method.

public function store()
{
    $user = new User();
    $user->email = Input::get('email');
    $user->password = Input::get('password');


    $dealership = new Dealership();
    $dealership->name = Input::get('dealership_name');

    $user->push();
    return "User Saved";

}

Trying to use $user->push(); User data gets updated, but dealership is not created or updated.

推荐答案

Eloquent's push() saves the model and its relationships, but first you have to tell what you want to be involved in the relationsship.

Since your user-model/table holds the id of the dealership, I assume that a user can belong to only one dealership, so the relationship should look like this:

User Model:

public function dealership()
{
  return $this->belongsTo('Dealership');
}

Dealership Model:

public function users()
{
  return $this->hasMany('User');
}

To save a User from the Dealership perspective, you do this:

$dealership->users()->save($user);

To associate a dealership with a user, you do this:

$user->dealership()->associate($dealership);
$user->save();

Laravel相关问答推荐

如何返回Blade Laravel 中的按钮?

使用两个日期之间的范围获取两列之间的记录,同时搜索过滤条件

LARAVEL 从多个表中获取重复的行

分页计数(*)查询问题

集成测试模拟外观与注入模拟

在Laravel 5中通过ID和所有递归获取记录

Laravel 5.2 中的正则表达式验证

Laravel 框架类在 PHPUnit 数据提供程序中不可用

Laravel 扩展验证自定义消息

在 laravel 5.2 中禁用特定路由的 Web 中间件

如何在 Laravel 5.5 中为选定的请求类设置自定义响应

使用模型工厂、一对一和一对多关系定义 Laravel 外键,而不创建不必要的模型

Laravel上传文件无法写入目录

在Lumen框架中启用会话

如何运行artisan命令计划:在托管服务器上运行? (Laravel )

Laravel Eloquent - 加入表时防止覆盖值

如何在 Laravel 4 中组织不同版本的 REST API 控制器?

如何在 Laravel 中 Refresh刷新用户对象?

无法在控制器的构造函数上调用 Auth::user()

Laravel 5 Illuminate\Http\Request 的方法不允许静态调用