Laravel一对多的关系麻烦

时间:2015-03-09 19:54:01

标签: laravel laravel-5

在数据库中有15个一对多的表,一切正常,但现在当我尝试添加一个表时,我收到了这个错误。我试过谷歌5-6解决方案,但我无法解决问题。 artikal_naruzba表工作正常。我的所有桌子都是空的!

错误

[Illuminate\Database\QueryException]

    SQLSTATE[HY000]: General error: 1215 Cannot add`enter code here` foreign key constraint (SQL: alter table `Narudzbe` add constraint narudzbe_kupac_id_foreign foreign key (`kupac_id`) references `kupci` (`id`))

      [PDOException]
      SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint

表Narudzba

public function up()
    {
        Schema::create('Narudzbe', function(Blueprint $table)
        {
            $table->increments('id');
            $table->integer('kupac_id')->unsigned();
            $table->foreign('kupac_id')->unsigned()->references('id')->on('kupci');
            $table->integer('BrojNarudzbe');
            $table->boolean('Status')->default(1);
            $table->boolean('Otkazano')->default(0);
            $table->timestamps();
        });



        Schema::create('artikal_naruzba', function(Blueprint $table){
            $table->increments('id');
            $table->integer('artikal_id')->unsigned()->index();
            $table->foreign('artikal_id')->references('id')->on('artikli')->onDelete('cascade');

            $table->integer('narudzba_id')->unsigned()->index();
            $table->foreign('narudzba_id')->references('id')->on('Narudzbe')->onDelete('cascade');

            $table->timestamps();
        });

    }

表Kupac

public function up()
    {
        Schema::create('kupci', function(Blueprint $table)
        {
            $table->increments('id');
            $table->string('ime');
            $table->string('prezime');
            $table->string('email')->unique();
            $table->string('lozinka', 60);
            $table->string('telefon', 30);
            $table->timestamps();
        });
    }

Naruzba模型

class Narudzba extends Model {

    protected $table = 'Narudzbe';

    public function kupac(){
        return $this->belongsTo('App\Kupac');
    }

    public function artikli(){

        return $this->belongsToMany('App\Artikal');
    }
}

Kupac模型

class Kupac extends Model {

    protected $table = 'kupci';

    public function narudzba(){
        return $this->hasMany('App\Narudzba');
    }

}

1 个答案:

答案 0 :(得分:0)

您在narudzba_id表无符号数据类型中声明artikal_naruzba。 但是您的原始Narudzbe表具有id而没有指定您在artikal_naruzba

中作为外键引用的unsigned

请仔细检查字段数据类型和长度。可能存在不匹配。 如需进一步,请访问: http://laravel.com/docs/5.0/schema#foreign-keys

$table->integer('narudzba_id')->unsigned()->index();
                $table->foreign('narudzba_id')->references('id')->on('Narudzbe')->onDelete('cascade');