【问题标题】:Laravel inserting data to a table which has 2 "BelongsTo"Laravel 将数据插入到具有 2 个“BelongsTo”的表中
【发布时间】:2018-09-15 10:29:14
【问题描述】:

我想将数据插入到一个具有 2 个“BelongsTo”关系的表(称为 Startups)中,我在一个好的 Laravel 文档中找到了如何使用一个表(一对多)来执行此操作,但我是这方面的初学者而且我不知道如何在一个公用表 (Sturtups) 中插入与 2 个不同表 (Categories - Contacts) 相关的数据,为了更好地理解这一点,请参阅下面附上的图片

这是我的代码(请不要关注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

附加信息:我有这个错误: “一般错误:1364 字段 'contact_id' 没有默认值” 我知道为什么会发生该错误(我正在尝试创建没有联系人 ID 的启动)

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

感谢大家的帮助!

【问题讨论】:

标签: php laravel eloquent relational-database


【解决方案1】:

您的问题的答案是:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-26
    • 2015-09-08
    • 1970-01-01
    相关资源
    最近更新 更多