Qasim Ali
Qasim Ali

Reputation: 597

How to get and store parent table id into its child laravel

I have searched alot to find a better way. I already read on Laravel docs that

Eloquent will try to match the parent id from the child model to an id on the parent model.

I have and Idea and Document tables. And they have 1:M relationship. an Idea can have many documents and a document can only relate to one Idea.

I am unable to get parent table id to store.

Controller Function:

public function storeDocuments(DocumentRequest $request) {

  if($request->hasFile('doc_name')) {
      $filename = $request->file('doc_name')->getClientOriginalName();
      $moveFile = $request->file('doc_name')->move('documents/', $filename);
    }
    $doc = new Document();
    $doc->doc_name = $moveFile;
    $doc->save();
}

Document Model:

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

Idea Model:

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

Please explain the procedure of storing id of parent table into child table.Thanks!

Edit:

public function storeDocuments(DocumentRequest $request) {

    if($request->hasFile('doc_name')) {
        $filename = $request->file('doc_name')->getClientOriginalName();
        $moveFile = $request->file('doc_name')->move('documents/', $filename);
    }
    $doc = new Document();
    $doc->doc_name = $moveFile;
    $idea = Idea::find(1); //how to get idea_id here???????
    $idea->documents()->save($doc);
    return back();
}

I am very confused about this relation. working for while now and cant figure out.

Idea Schema:

public function up()
{
    //
    Schema::create('ideas', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id')->unsigned();
        $table->string('idea_title');
        $table->string('idea_info', 150);
        $table->string('idea_image');
        $table->string('selection');
        $table->longText('idea_description');
        $table->string('idea_location');
        $table->integer('idea_goal')->unsigned();
        $table->integer('pledge_amount')->unsigned();
        $table->string('set_equity')->nullable();
        $table->boolean('status')->default(0);
        $table->rememberToken();
        $table->timestamps();
        $table->softDeletes();
    });
}

Document Schema:

public function up()
{
    //
    Schema::create('documents', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('idea_id')->unsigned();
        $table->string('doc_name');
        $table->rememberToken();
        $table->timestamps();
        $table->softDeletes();
    });
}

Upvotes: 1

Views: 2798

Answers (1)

Tacsiazuma
Tacsiazuma

Reputation: 776

You don't need to manually set the ID, Eloquent does that for you:

The documents() returns a relationship which have a save method to store related models:

$idea->documents()->save($document);

It even has a saveMany() method to store many at once:

$idea->documents()->saveMany($documents);

UPDATE:

You should put that to your repository class. The foreign_key assumed to be idea_id, but with a sec ond parameter passed to the hasMany method you can override that if you already built the schema:

public function documents() {
    $this->hasMany("\App\Document", "your_foreign_key_here");
}

The related laravel docs are here.

Hope that helps.

UPDATE:

$idea_id = $idea->id; // assuming the ID field is not overriden in your schema/model

It simply using the idea table's primary key value, the same value you used in the find method. The one to many relations are working by a join in default and using the parents primary key value to join the child tables record.

IDEA           DOCUMENT   
-----------   ---------------
|   id    |-->| idea_id | id |
|   1     |   |    1    |  1 |
|   2     |   |    1    |  2 |
-----------   ---------------- 

Okay, so reproducing the queries in SQL. Basically each model represents a table, and each record in the table represents an instance of that model class. To query them, you need to have a primary key field on that table, so every record is identified by that field. It defaults to 'id' in eloquent.

When we speak about relationships, then we need another field to join the related tables on. In this particular situation it will be the idea_id field inside the document table. When fetching documents associated with an idea whose ID is 1, then the related documents will have 1 in their 'idea_id' field, because they are connected to that idea with id = 1. SQL query looks like sg like:

SELECT * FROM document JOIN idea ON document.idea_id = idea.id WHERE idea.id = 1

But as I've already said, you don't have to explicitly store that value, because eloquent does it.

Could you show me your document and idea tables or migration schemas please?

UPDATE

public function storeDocuments(DocumentRequest $request) {

if($request->hasFile('doc_name')) {
    $filename = $request->file('doc_name')->getClientOriginalName();
    $moveFile = $request->file('doc_name')->move('documents/', $filename);
}
$doc = new Document();
$doc->doc_name = $moveFile;
$idea = Idea::find(1); // idea id is 1, but i guess it'll come from the route or sg like that in a real world scenario
$idea_id = $idea->id; // the idea id : in this case = 1
$idea->documents()->save($doc);
return back();

}

Upvotes: 1

Related Questions