m.mahmoudi
1 سال پیش توسط m.mahmoudi مطرح شد
2 پاسخ

nullable در لاراول

با سلام.
من فرمی دارم که عکس آپلود میکنه و حالا میخوام ارتباطی بزنم که این عکس میتونه متعلق به جدول هتل باشه و هم مقاله و هم اینکه میتونه فقط مرتبط به یکی از این جداول باشه من باید چکار کنم؟
جدول images هست.

    public function up()
    {
        Schema::create('images', function (Blueprint $table) {
            $table->id();
            $table->foreignId('hotel_id')->nullable()->constrained('hotels')->cascadeOnUpdate()->cascadeOnUpdate();
            $table->foreignId('article_id')->nullable()->constrained('articles')->cascadeOnUpdate()->cascadeOnUpdate();
            $table->string('image');
            $table->timestamps();
        });
    }

این هم خطا

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`hotel_reserve`.`images`, CONSTRAINT `images_article_id_foreign` FOREIGN KEY (`article_id`) REFERENCES `articles` (`id`) ON UPDATE CASCADE)

mhyeganeh@
ali.bayat@
endworld@


ثبت پرسش جدید
djnack
@Dj.nack666 1 سال پیش مطرح شد
0

دوست عزیز شما نمیتونین روی رابطه چیزی تعیین کنی.
شما باید روی فیلد ستون ها دستور null وارد کنی.

$table->unsignedBigInteger('user_id')->nullable();

$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');

djnack
@Dj.nack666 1 سال پیش مطرح شد
0

البته اگه بخوای یک عکس رو به چند مدل نسبت بدی بهتر از پلی مورفیس استفاده کنی.

        Schema::create('images', function (Blueprint $table) {
            $table->id();
            $table->string('path');
            $table->string('alt')->nullable();
            $table->timestamps();

        });

        Schema::create('imageables', function (Blueprint $table) {
            $table->string('detail')->nullable();
            $table->integer("imageables_id");
            $table->string("imageables_type");
            $table->unsignedBigInteger('image_id')->unsigned();

            $table->foreign('image_id')->references('id')->on('images')->onDelete('cascade');
        });

برای ارسال پاسخ لازم است وارد شده یا ثبت‌نام کنید

ورود یا ثبت‌نام