[英]How can I insert multiple emails in Laravel?
I want to insert multiple emails of a user into a different table in Laravel. 我想将用户的多封电子邮件插入Laravel中的另一个表中。 Is it possible?
可能吗?
Here is code: 这是代码:
use App\PersonData;
class PersonDataController extends Controller
{
public function store(Request $request)
{
$user = new PersonData();
return PersonData::store($request->person_data,$user);
}
}
here is model 这是模特
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;
}
}
here is 2nd model where want to insert multiple emails 这是要插入多个电子邮件的第二个模型
class CustomerEmail extends Model
{
protected $fillable = ['emails','person_data_id'];
public function persondata()
{
return $this->belongsTo(PersonData::class);
}
}
and final json code 和最终的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"
}
}
As I understood your question. 据我了解您的问题。 what you are looking for is
saveMany()
function for a one-to-many
relationship. 您正在寻找的是
one-to-many
关系的saveMany()
函数。
or may be i misunderstood your question 还是我可能误会了你的问题
// 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.