mercredi 16 décembre 2015

Laravel 5 - defining relationships

everything was working fine with a single Model, but now I am implementing more, I have noticed an issue.

I have several document Models which represent a different type of document. For now, let's say I have DocumentA and DocumentB.

Each Document allows file uploads, so I have created a FileUpload Model. A Document can have many FileUploads.

So, seems pretty straight forward at this point. My FileUpload table has a documentId field, which is a reference to the id field of the Document that is using it.

In DocumentA, I have something like so

public function uploadFile()
{
    return $this->hasMany('App\UploadFile', 'documentId');
}

So DocumentA can have many UploadFiles, linked by the documentId.

DocumentB has the same function within its Model.

My problem lies with the UploadFiles model. Firstly, this model now has two belongTo events e.g.

public function documentA()
{
    return $this->belongsTo('App\DocumentA', 'documentId');
}

public function documentB()
{
    return $this->belongsTo('App\DocumentB', 'documentId');
}

This could be the problem, not sure if I can have multiple belongs to? My immediate problem however is to do with the migration of the doc_file table. At the moment I have this

Schema::table('doc_file', function (Blueprint $table) {
    $table->integer('documentId')->unsigned()->default(0);
    $table->foreign('documentId')->references('id')->on('document_a')->onDelete('cascade');
});

Schema::table('doc_file', function (Blueprint $table) {
    $table->integer('documentId')->unsigned()->default(0);
    $table->foreign('documentId')->references('id')->on('document_b')->onDelete('cascade');
});

So I am trying to provide foreign keys to my documents. When I try to migrate, it tells me that

Column already exists: 1060 Duplicate column name documentId

Am I handling my relationships correctly? Essentially, I have many documents, and each document can have many files.

Any assistance with my database relationships appreciated.

Many thanks



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire