保存相关记录在laravel [英] Saving related records in laravel

查看:97
本文介绍了保存相关记录在laravel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have users, and users belong to a dealership.

在用户注册时,我正在尝试保存新用户和新的经销商。

Upon user registration, I'm trying to save a new user, and a new dealership.

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

User database has a dealership_id column, which I want to be populated with the ID of the newly created dealership.

这是我现在在 UserController store方法中的代码。

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";

}

尝试使用 $ user- > push(); 用户数据更新,但不会创建或更新经销商。

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

推荐答案

Eloquent的 push()保存模型及其关系,首先你必须告诉你要参与的关系。

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:

用户模型:

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

经销商型号:

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆