【问题标题】:Integrity constraint violation: 1452 fillable also not worked违反完整性约束:1452 可填充也不起作用
【发布时间】:2019-01-22 20:35:57
【问题描述】:

我有一个数据透视表 category_product 我想在其中存储 product_id category_id

它在 phpmyadmin 中可以正常工作,但在 laravel 中不起作用

我尝试了可填充但仍然无法正常工作

PDOException::("SQLSTATE[23000]: 完整性约束违规:1452 无法添加或更新子项 行:外键约束失败 (new.category_product, CONSTRAINT category_product_category_id_foreign FOREIGN KEY (category_id) REFERENCES categories (id) ON DELETE CASCADE)")

Category.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    protected $fillable = ['parent_id'];

    public function childs() {
        return $this->hasMany('App\Category', 'parent_id');
    }

    public function products()
    {
        return $this->belongsToMany('App\Product');
    }
}


Product.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    public function presentPrice() {
        return "Rs ".number_format($this->price);
    }

    public function categories() {
        return $this->belongsToMany('App\Category');
    }
}

CategoryProduct.php 

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class CategoryProduct extends Model
{
    protected $table = 'category_product';

    protected $fillable = ['product_id', 'category_id'];
}

2018_08_15_224031_create_category_product_table.php

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateCategoryProductTable extends Migration
{

        /**
         * Run the migrations.
         *
         * @return void
         */
        public function up()
        {
            Schema::create('category_product', function (Blueprint $table) {
                $table->increments('id');

                $table->integer('product_id')->unsigned()->nullable();
                $table->foreign('product_id')->references('id')
                      ->on('products')->onDelete('cascade');

                $table->integer('category_id')->unsigned()->nullable();
                $table->foreign('category_id')->references('id')
                      ->on('categories')->onDelete('cascade');
                $table->timestamps();
            });
        }

        /**
         * Reverse the migrations.
         *
         * @return void
         */
        public function down()
        {
            Schema::dropIfExists('category_product');
        }
    }

ProductTableSeeder.php

<?php

use App\Product;
use Illuminate\Database\Seeder;

class ProductsTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        // Laptops
        for ($i=1; $i <= 7; $i++) {
            Product::create([
                'name' => 'Laptop '.$i,
                'slug' => 'laptop-'.$i,
                'details' => [13,14,15][array_rand([13,14,15])] . ' inch, ' . [1, 2, 3][array_rand([1, 2, 3])] .' TB SSD, 32GB RAM',
                'price' => rand(30000, 60000),
                'description' =>'Lorem '. $i . ' ipsum dolor sit amet, consectetur adipisicing elit. Ipsum temporibus iusto ipsa, asperiores voluptas unde aspernatur praesentium in? Aliquam, dolore!',
                'image' => 'products/dummy/laptop-'.$i.'.jpg',
                'images' => '["products\/dummy\/laptop-2.jpg","products\/dummy\/laptop-3.jpg","products\/dummy\/laptop-4.jpg"]',
            ])->categories()->attach(4);
        }

        // Phones
        for ($i = 1; $i <= 7; $i++) {
            Product::create([
                'name' => 'Phone ' . $i,
                'slug' => 'phone-' . $i,
                'details' => [16, 32, 64][array_rand([16, 32, 64])] . 'GB, 5.' . [7, 8, 9][array_rand([7, 8, 9])] . ' inch screen, 4GHz Quad Core',
                'price' => rand(20000, 50000),
                'description' => 'Lorem ' . $i . ' ipsum dolor sit amet, consectetur adipisicing elit. Ipsum temporibus iusto ipsa, asperiores voluptas unde aspernatur praesentium in? Aliquam, dolore!',
                'image' => 'products/dummy/phone-'.$i.'.jpg',
                'images' => '["products\/dummy\/phone-2.jpg","products\/dummy\/phone-3.jpg","products\/dummy\/phone-4.jpg"]',
            ])->categories()->attach(2);
        }

        // Cameras
        for ($i = 1; $i <= 11; $i++) {
            Product::create([
                'name' => 'Camera ' . $i,
                'slug' => 'camera-' . $i,
                'details' => 'Full Frame DSLR, with 18-55mm kit lens.',
                'price' => rand(40000, 150000),
                'description' => 'Lorem ' . $i . ' ipsum dolor sit amet, consectetur adipisicing elit. Ipsum temporibus iusto ipsa, asperiores voluptas unde aspernatur praesentium in? Aliquam, dolore!',
                'image' => 'products/dummy/camera-'.$i.'.jpg',
                'images' => '["products\/dummy\/camera-3.jpg","products\/dummy\/camera-4.jpg","products\/dummy\/camera-5.jpg"]',
            ])->categories()->attach(5);
        }

                // Select random entries to be featured
        Product::whereIn('id', [1, 6, 8, 12, 15, 18, 20, 21, 23,22, 24, 13, 10])->update(['featured' => true]);

    }
}

【问题讨论】:

    标签: sql database laravel-5 foreign-keys mass-assignment


    【解决方案1】:

    您想同步您的产品和类别,但是 mysql 找不到给定的 category_id。

    可能您忘记在类别表上创建这些行。

    【讨论】:

    • 兄弟它的作品来自 php 我的管理员,所以 mysql dnt 怎么可能知道在哪里插入这些 ids
    • @AhmedRaza 这不是关于在哪里,而是关于什么。我认为mysql找不到类别2。您确定表中存在类别吗?
    • 你是正确的类别表播种器需要先播种然后产品表播种器才能正确播种
    猜你喜欢
    • 2016-08-11
    • 2015-11-27
    • 2016-05-25
    • 2021-07-23
    • 2012-06-14
    • 1970-01-01
    • 2020-01-14
    • 2021-12-13
    相关资源
    最近更新 更多