【发布时间】:2020-01-12 13:28:40
【问题描述】:
我有 3 张桌子:
User
- id
- email
UserAccount
- id
- user_id
- account_id
Account
- id
- user_id
Verification
- id
- user_id
- guid
每当我尝试添加user 时,我都会尝试创建一个帖子,它会自动添加一个带有空字段但带有user_id 的account,Verification 表也带有user_id,在同时,一旦创建了Account,它还应该记录UserAccountuser_id 和account_id,但我使用多对多关系belongsToMany 和sync 结束了这个错误。如何添加 acct_id 和 user_id with eloquent?
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'acct_id' cannot be null (SQL: insert into `user_accounts` (`acct_id`, `user_id`) values (?, 17))
这是我迄今为止尝试过的。
控制器.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
]);
用户.php
public function account()
{
return $this->hasMany(Account::class);
}
public function userAccount()
{
return $this->belongsToMany(User::class, UserAccount::class, 'user_id', 'id');
}
用户帐户.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');
}
验证.php
public function user()
{
return $this->belongsTo(User::class, 'user_id', 'id');
}
帐户.php
public function user()
{
return $this->hasMany(User::class);
}
public function userAccount()
{
return $this->belongsTo(UserAccount::class);
}
我尝试使用此功能并且完全可以正常工作,但很确定这就是它与 eloquent 一起工作的方式。
$userAcct = new UserAccount();
$userAcct->create([
'user_id' => $user->id,
'acct_id' => $accounts->id
]);
有什么想法吗?
我也确实发现了这个相关的问题 (Laravel hasManyThrough)
【问题讨论】:
-
可以更新数据库结构吗?因为看起来你的
User <=> Account关系应该是一个Many to Many,UserAccount作为支点。 (我的答案取决于你的答案) -
@Shizzen83 是的,我需要做什么?
-
将所有内容写成答案,等待 5 分钟
-
@Shizzen83 不用担心我可以等
标签: php laravel laravel-5 eloquent