gpt4 book ai didi

php - Laravel 一对一的关系。将用户名从表保存到另一个表

转载 作者:行者123 更新时间:2023-11-29 18:06:39 26 4
gpt4 key购买 nike

TLDR:如何创建一个表到另一个表的关系?例如,我希望用户表中的更改自动反射(reflect)到供应商表中?就像它只是从用户表中引用一样。

我有这两张 table

========================
USER table

1. id
2. username
3. password
4. name
========================

========================
SUPPLIER table

1. id
2. username
3. name
========================

每次我添加新用户时,它都应该自动保存到供应商表中。这就是我所做的:

function saveUser($postdata) {
$newUser= new \App\UserModel;
$newUser->email = $postdata['email'];
$newUser->password = $postdata['password'];
$newUser->name = $postdata['name'];
$newUser->save();

$this->saveSupplier($postdata['email'], $postdata['name']);
}

function saveSupplier($email, $name) {
$newSupplier = new \App\SupplierModel;
$newSupplier->email = $email;
$newSupplier->name = $name;
$newSupplier->save();
}

你看,这不是一种正确的关系。这就像手动保存到两个表中一样。如何使供应商表依赖于用户表?例如,每次我在用户表中进行更改时,它都会自动反射(reflect)到供应商表中,而无需触发更新方法。

最佳答案

实现此目的的一种方法是在您的启动方法中注册和事件用户模型。

protected static function boot()
{
parent::boot();

static::created(function($user) {
Supplier::create([
'username' => $user->username //or email or whatever you have.
'name' => $user->name
]);
});
}

关于php - Laravel 一对一的关系。将用户名从表保存到另一个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47770884/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com