【问题标题】:Laravel eloquent insert data with multiple relationshipLaravel eloquent 插入具有多重关系的数据
【发布时间】: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_idaccountVerification 表也带有user_id,在同时,一旦创建了Account,它还应该记录UserAccountuser_idaccount_id,但我使用多对多关系belongsToManysync 结束了这个错误。如何添加 acct_iduser_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 ManyUserAccount 作为支点。 (我的答案取决于你的答案)
  • @Shizzen83 是的,我需要做什么?
  • 将所有内容写成答案,等待 5 分钟
  • @Shizzen83 不用担心我可以等

标签: php laravel laravel-5 eloquent


【解决方案1】:

首先,您应该从account 表中删除user_id,因为它已被链接两个表的user_account 引用。此外,如果你想利用 Eloquent 约定来猜测表名和字段,你应该确保你的表被命名为 usersaccountsverificationsaccount_user

用户.php

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

帐户.php

public function users()
{
    return $this->belongsToMany(User::class);
}

如果account_user 仅存在于链接 2 个表,则 UserAccount 模型将毫无用处。

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

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

<?php

namespace App\Observers;

use App\Account;
use App\Verification;

class UserObserver
{
    /**
     * Handle the User "created" event.
     *
     * @param  \App\User  $user
     * @return void
     */
    public function created(User $user)
    {
        (new Verification)->user()->associate($user);
        $account = new Account;
        $account->save();
        $user->accounts()->attach([
            $account->id
        ]);
    }
}

【讨论】:

  • 重读后,我可能无法理解您的表格,请问您可以确认用户和帐户之间的关系吗? 1 个用户 n 个帐户或 n 个用户 n 个帐户?
  • 用户可以有很多账户,同样的,账户也可以有很多用户。尝试使用您的解决方案,但 Base table or view not found: 1146 Table 'db.account_user' doesn't exist 如果有什么我错过的东西,我仍在寻找模型
  • 是的,我告诉过你 Eloquent 会尝试猜测数据透视表名称:按字母顺序将 2 个表的 _ 连接起来 => account_user。您有 2 个选择:重命名 SQL 表或在此处添加您的数据透视表名称 $this-&gt;belongsToMany(Account::class, here);return $this-&gt;belongsToMany(User::class, here);
  • 我更改了 SQL 表,这是输出 Column not found: 1054 Unknown column 'account_id' in 'field list' (SQL: insert into account_user` (account_id, user_id) 值 (?, 46)), for the pivot name what should i put on the "here" in belongsToMany`?
  • 如果您更新了数据透视表名称,则无需更改任何其他内容;) 请列出此表的字段
【解决方案2】:
// Post Model
 public function user()
    {
        return $this->belongsTo('App\User');
    }
    public function categories()
    {
        return $this->belongsToMany('App\Category')->withTimestamps();
    }
    public function tags()
    {
        return $this->belongsToMany('App\Tag')->withTimestamps();
    }

//User Model
 public function posts()
    {
        return $this->hasMany('App\Post');
    }

//Category Model

 public function posts()
    {
        return $this->belongsToMany('App\Post')->withTimestamps();
    }

//Tag Model 

public function posts()
    {
        return $this->belongsToMany('App\Post')->withTimestamps();
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-30
    • 1970-01-01
    • 2015-05-19
    • 2018-10-09
    • 2015-03-02
    • 1970-01-01
    • 2022-01-19
    • 2015-08-05
    相关资源
    最近更新 更多