【问题标题】:Laravel 8 Eloquent Many To Many insert into pivot table not workingLaravel 8 Eloquent 多对多插入数据透视表不起作用
【发布时间】:2021-12-30 14:44:15
【问题描述】:

我正在尝试将数据插入到 AdvertisementAdvertisementCategory 之间的数据透视表中。首先,是的,就我而言,一个广告可以有很多类别。 顺便说一句:

我所有的模型都继承自我的 DatabaseObject 类。

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class DatabaseObject extends Model
{
    /**
     * Disables the
     * created_at and updated_at column creation
     * @var bool
     */
    public $timestamps = false;
}

这是我的广告模型:

<?php

namespace App\Models\Advertisement;

use App\Models\DatabaseObject;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;

/**
 * Basic Advertisement
 */
class Advertisement extends DatabaseObject
{
    use HasFactory;

    /**
     * Custom table name
     * @var string
     */
    protected $table = 'advertisement';

    public $fillable = ['name', 'description', 'sellingType', 'advertisementType', 'sellingPrice'];

    /**
     * A Advertisement has one AdvertisementCategory
     * @return BelongsToMany
     */
    public function advertisementCategories(): BelongsToMany
    {
        return $this->belongsToMany(AdvertisementCategory::class
            , 'advertisement2advCategory'
            , 'advertisementCategory_id'
            , 'advertisement_id');
    }
}

这是我的 AdvertisementCategory 模型:

<?php

namespace App\Models\Advertisement;

use App\Models\DatabaseObject;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;

class AdvertisementCategory extends DatabaseObject
{
    /**
     * Custom table name
     * @var string
     */
    protected $table = 'advertisementCategory';

    /**
     * A AdvertisementCategory can have many advertisements
     * @return BelongsToMany
     */
    public function advertisements(): BelongsToMany
    {
        return $this->belongsToMany(Advertisement::class
            , 'advertisement2advCategory'
            ,'advertisement_id'
            ,'advertisementCategory_id');
    }
}

这是我的数据透视表对象:

<?php

namespace App\Models\Advertisement;

use Illuminate\Database\Eloquent\Relations\Pivot;

class Advertisement2AdvertisementCategory extends Pivot
{
    /**
     * Custom name for the table
     * @var string
     */
    protected $table = 'advertisement2advCategory';
}

这是迁移创建:

        Schema::create('advertisement2advCategory', function (Blueprint $table) {
            $table->id();
            $table->foreignId('advertisement_id');
            $table->foreign('advertisement_id')
                ->references('id')
                ->on('advertisement')
                ->onDelete('cascade');
            $table->foreignId('advertisementCategory_id');
            $table->foreign('advertisementCategory_id')
                ->references('id')
                ->on('advertisementCategory')
                ->onDelete('cascade');
        });

这是我在尝试从请求中插入时收到的错误:

        $newAdvertisement = new Advertisement();
        $newAdvertisement->name = $request->name;
        $newAdvertisement->description = $request->description;
        $newAdvertisement->sellingType = $request->sellingType;
        $newAdvertisement->advertisementType = $request->advertisementType;
        $newAdvertisement->sellingPrice = $request->sellingPrice;
        $newAdvertisement->createdAt = date('Y-m-d H:i:s');
        $newAdvertisement->images = $allImages;
        $newAdvertisement->unlockedAt = null;
        $newAdvertisement->advertisementCategories()->attach($request->selectedCategory);
        $newAdvertisement->save();
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'advertisementCategory_id' cannot be null (SQL: insert into `advertisement2advCategory` (`advertisementCategory_id`, `advertisement_id`) values (?, 7)) 

【问题讨论】:

  • 我觉得你们的关系不是Many to Many而是hasMany,因为一个广告可以有很多类别。

标签: php mysql laravel eloquent


【解决方案1】:

您的问题只是操作顺序。 您正在尝试保存多对多房地产的记录,而 $newAdvertisement 尚未保存,因此它没有自己的 ID(这就是您收到错误 Column 'advertisementCategory_id' cannot be null 的原因)。

先保存$newAdvertisement,然后再添加关系。

$newAdvertisement->save();
$newAdvertisement->advertisementCategories()->attach($request->selectedCategory);

【讨论】:

  • 感谢这有帮助,但现在我得到一个新错误:(PHP SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`umarketdb`.`advertisement2advCategory`, CONSTRAINT `advertisement2advcategory_advertisement_id_foreign` FOREIGN KEY (`advertisement_id`) REFERENCES `advertisement` (`id`) ON DELETE CASCADE) (SQL: insert into `advertisement2advCategory` (`advertisementCategory_id`, `advertisement_id`) values (3, 7))
  • 发现了我的问题。我在数据透视表中添加了一个 PK。删除后一切正常。
猜你喜欢
  • 2023-02-05
  • 1970-01-01
  • 2014-12-13
  • 2014-12-07
  • 1970-01-01
  • 2013-04-29
  • 2015-02-04
  • 2017-04-11
  • 1970-01-01
相关资源
最近更新 更多