dqdjfb2325 2018-10-03 11:28
浏览 63

如何在Laravel中插入多个电子邮件?

I want to insert multiple emails of a user into a different table in 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

{
  "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"
  }
}
  • 写回答

1条回答 默认 最新

  • dongpou7275 2018-10-03 11:54
    关注

    As I understood your question. what you are looking for is saveMany() function for a one-to-many relationship.

    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);
    
    评论

报告相同问题?

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号