普通网友 2018-09-15 10:29
浏览 110
已采纳

Laravel将数据插入到具有2个“BelongsTo”的表中

I want to insert data to one table (called Startups) which has 2 "BelongsTo" relations, I found how to do this with one table (One to Many) in a good Laravel's documentation but I'm beginner in this area and I don't know how to insert data to related to 2 different tables (Categories - Contacts) in one common table (Sturtups), to understand this better please see the image I attached below

Here is my code (please don't pay attention to Sessions, it doesn't matter in that case):

$category_id = Session::get('category_id');
        $country_id = Session::get('country_id');

        $new_contact = new Contact([
            'name'  => Session::get('contact_name'),
            'phone' => Session::get('contact_phone'),
            'email' => Session::get('contact_email')
        ]);
        $country = Country::find($country_id);
        $country->contacts()->save($new_contact);

        $new_startup = new Startup([
            'name'        => Session::get('startup_name'),
            'description' => Session::get('startup_description'),
            'url'         => Session::get('startup_url'),
            'logo'        => Session::get('logo_name')
        ]);

        $category = Category::find($category_id);
        $category->startups()->save($new_startup);

        $contact = Contact::find( $country->contacts()->id );
        $contact->startups()->save($new_startup);

Database Relations image: image of relations between tables in the DB

Additional info: I have this error: "General error: 1364 Field 'contact_id' doesn't have a default value" I know why that error happens (I'm trying to create Startup without id of contact)

I just want to know how insert data in that case

Thank you guys for any help!

  • 写回答

1条回答 默认 最新

  • 普通网友 2018-09-15 10:35
    关注

    Answer to your question is:

    make that field nullable in database migration so this error will not occur

    $table->unsignedInteger('contact_id')->nullable();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大