Laravel保存到具有多个表的数据库的多个表

时间:2018-06-25 23:53:27

标签: laravel eloquent

我在数据库中有一个交易表。交易表的关系是,客户可以发送许多交易。分支可以有许多事务,而事务处理程序可以为许多事务提供服务。我已经定义了模型和关系。但是不知道如何保存关系,因为先保存一个会使其他fk为空。有什么方法可以一次保存所有内容,或者我的数据库关系错误?

我的模式是

enter image description here

保存关系的控制器代码是

//Save models related to transactions
        $transaction = new Transaction($request->input('partCTransaction'));
        //Customer can have many transactions
        $customer->transactions()->save($transaction);
        //branch has many reporting entities and a branch handles many transactions
        $branch->transactions()->save($transaction);
        //A transaction handler handles different transactions
        $transactionHandler->transactions()->save($transaction);

关于如何解决此问题的任何想法。

我的错误是

General error: 1364 Field 'branch_id' doesn't have a default value (SQL: insert into `transactions` (`date`, `ref_number`, `customer_id`, `updated_at`, `created_at`) values (, , 9, 2018-06-25 23:36:11, 2018-06-25 23:36:11))

1 个答案:

答案 0 :(得分:1)

您的Transaction模型应该具有customerbranchtransactionHandler belongsTo关系:

public function customer()
{
    return $this->belongsTo(Customer::class);
}

public function branch()
{
    return $this->belongsTo(Branch::class);
}

public function transactionHandler()
{
    return $this->belongsTo(TransactionHandler::class);
}

belongsTo关系具有一个associate()方法,该方法设置关系字段,但不保存记录。您可以使用这些关系来设置所有适当的关系,然后在完成后调用save()

$transaction = new Transaction($request->input('partCTransaction'));
$transaction->customer()->associate($customer);
$transaction->branch()->associate($branch);
$transaction->transactionHandler()->associate($transactionHandler);
$transaction->save();

仅附带说明一下,associate()返回了子模型,因此,如果您希望这种外观,可以将所有这些模型链接在一起:

$transaction = new Transaction($request->input('partCTransaction'));
$transaction
    ->customer()->associate($customer)
    ->branch()->associate($branch)
    ->transactionHandler()->associate($transactionHandler)
    ->save();