Laravel雄辩地插入具有多个关系的数据

时间:2019-07-14 20:57:30

标签: php laravel laravel-5 eloquent

我有3张桌子:

User
    - id
    - email

UserAccount
    - id
    - user_id
    - account_id

Account
    - id
    - user_id

Verification
    - id
    - user_id
    - guid

每当我尝试添加一个user时,我都会尝试发布一个帖子,它将自动添加一个account带有空白字段但其中包含user_id的{​​{1}}还带有Verification的表,同时创建了user_id之后,它还应该记录Account UserAccountuser_id,但是我最终使用多对多关系account_idbelongsToMany。如何雄辩地添加syncacct_id

user_id

这是我到目前为止尝试过的。

Controller.php

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'acct_id' cannot be null (SQL: insert into `user_accounts` (`acct_id`, `user_id`) values (?, 17))

User.php

$user = new User();
$user->name = "Not set";
$user->email = $email;
$user->password = NULL;
$user->save();

$accounts = new Account();
$accounts->email = $email;
$user->account()->save($accounts);

$userAccount = new UserAccount();
$userAccount->userAccount()->sync([
   $user->id,
   $accounts->id
]);

UserACcount.php

public function account()
{
    return $this->hasMany(Account::class);
}

public function userAccount()
{
    return $this->belongsToMany(User::class, UserAccount::class, 'user_id', 'id');
}

Verification.php

public function user()
{
    return $this->hasMany(User::class, 'user_id', 'id');
}

public function account()
{
    return $this->hasMany(Account::class, 'acct_id', 'id');
}

public function userAccount()
{
    return $this->belongsToMany(Account::class, UserAccount::class, 'acct_id', 'user_id');
}

Account.php

public function user()
{
    return $this->belongsTo(User::class, 'user_id', 'id');
}

我尝试使用此功能,并且完全可以正常工作,但是可以肯定的是,这是雄辩的工作方式。

public function user()
{
    return $this->hasMany(User::class);
}

public function userAccount()
{
    return $this->belongsTo(UserAccount::class);
}

有什么想法吗?

我也确实发现了这个相关问题(Laravel hasManyThrough

2 个答案:

答案 0 :(得分:1)

首先,应该从user_id表中删除account,因为链接两个表的user_account已经引用了它。此外,如果您想利用口才约定来猜测表名和字段,则应确保表名为usersaccountsverifications和{{1} }。

User.php

account_user

Account.php

public function accounts()
{
    return $this->belongsToMany(Account::class);
}

如果public function users() { return $this->belongsToMany(User::class); } 仅存在于链接2个表,则UserAccount模型是无用的。

然后,您可以使用观察者来获取基于事件的方法:每当创建用户时=>做某事

https://laravel.com/docs/5.8/eloquent#observers

account_user

答案 1 :(得分:0)

<div class="div1">
<img src="something.png" class="myImage">
</div>