【问题标题】:Inserting data into two different table with relation using Eloquent使用 Eloquent 将数据插入到两个具有关系的不同表中
【发布时间】:2019-07-05 14:13:33
【问题描述】:

我要表叫客户和地址。

客户表

id
customer_name
address_id

地址表

id
address

表单同时输入了客户姓名和地址。我想插入地址并获取地址 ID 并插入带有地址 ID 和客户名称的客户表。这可能吗?

我的模型是这样的

public function addCustomer($data)
{

    $this->table('address')->insertGetId([ 
        'address' => $data['address'],
    ]);

    $this->table('customers')->insertGetId([ 
        'customer_name' => $data['customer_name'],
        'address_id' => //how can I get address ID,
    ]);
}

如何从新插入的行中获取地址 ID?

谢谢。

【问题讨论】:

  • insertGetId() 返回插入的id
  • 我不需要使用 save() 吗?

标签: mysql eloquent


【解决方案1】:

你做得对。您需要初始化address id变量,并将其设置为customers表insert中的address_id

public function addCustomer($data)
{
    // storing address_id to the $address_id variable
    $address_id = $this->table('address')->insertGetId([ 
      'address' => $data['address'],
    ]);

    $this->table('customers')->insertGetId([ 
       'customer_name' => $data['customer_name'],
       'address_id' => $address_id 
       // setting address_id from the above address id
    ]);
}

【讨论】:

    【解决方案2】:
    public function addCustomer($data)
    {
        $address = $this->table('address')->insertGetId([ 
          'address' => $data['address'],
        ]);
    
        $this->table('customers')->insertGetId([ 
           'customer_name' => $data['customer_name'],
           'address_id' => $address 
        ]);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-20
      • 1970-01-01
      相关资源
      最近更新 更多