Laravel 将数据插入到 table 其中有 2 "BelongsTo"

Laravel inserting data to a table which has 2 "BelongsTo"

我想将数据插入一个 table(称为 Startups),它有 2 个 "BelongsTo" 关系,我找到了如何用一个 table(一对多)来做到这一点一份很好的 Laravel 文档,但我是这方面的初学者,我不知道如何在一个常见的 [=30] 中插入与 2 个不同 table 相关的数据(类别 - 联系人) =] (Sturtups),为了更好地理解这一点,请看我在下面附上的图片

这是我的代码(请不要关注Sessions,那样的话没关系):

$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);

数据库关系图片: image of relations between tables in the DB

附加信息:我有这个错误: "General error: 1364 Field 'contact_id' doesn't have a default value" 我知道为什么会发生该错误(我正在尝试创建没有联系人 ID 的 Startup)

我只想知道在那种情况下如何插入数据

谢谢大家的帮助!

你问题的答案是:

在数据库迁移中使该字段可为空,这样就不会发生此错误

$table->unsignedInteger('contact_id')->nullable();