我想将用户的多封电子邮件插入Laravel中的不同表中。 有可能吗?
这是代码:
use App\PersonData;
class PersonDataController extends Controller
{
public function store(Request $request)
{
$user = new PersonData();
return PersonData::store($request->person_data,$user);
}
}
这是模型
use App\CustomerEmail;
use App\SupplierEmail;
class PersonData extends Model
{
public function customeremails()
{
return $this->hasMany(CustomerEmail::class);
}
public function supplieremails()
{
return $this->hasMany(SupplierEmail::class);
}
public static function store($request,$user)
{
$user = fill($request);
$user->save();
return $user;
}
}
这是要插入多封电子邮件的第二种模式
class CustomerEmail extends Model
{
protected $fillable = ['emails','person_data_id'];
public function persondata()
{
return $this->belongsTo(PersonData::class);
}
}
和最终的json代码
{
"person_data": {
"first_name": "Customer",
"last_name": "customer_lastname",
"company_name": "new industry",
"gst_number": "no",
"type": "customer",
"customeremails": [
{
"person_data": 1,
"email": "relation@gmail.com"
}
],
"address": "house 123, city:ludhiana",
"phone_numbers": "8844845545",
"website": "www.google.com"
}
}
答案 0 :(得分:0)
据我了解您的问题。您正在寻找的是saveMany()
关系的one-to-many
函数。
或者可能是我误解了您的问题
// first gather all the emails to be saved after 'person data' is saved.
// because 'customer email' needs 'person data' id.
$customer_emails = collect();
foreach($request->person_data->customeremails as $email) {
$cutomer_email = CustomerEmail::make([
'email' => $email.email
]);
$customer_emails->push($customer_email);
}
// save 'person data' first
$person_data = PersonData::create([
// your person_data
]);
// this will automatically set 'person_data' foreign key on the 'customer email' table
// and save
$person_data->customeremails()->savemany($customer_emails);