我必须在称为客户和地址的表中
客户表
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?
谢谢。
答案 0 :(得分:0)
public function addCustomer($data)
{
$address = $this->table('address')->insertGetId([
'address' => $data['address'],
]);
$this->table('customers')->insertGetId([
'customer_name' => $data['customer_name'],
'address_id' => $address
]);
}
答案 1 :(得分:0)
您做得正确。您需要初始化地址ID 变量,并将其设置为客户表插入中的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
]);
}