blastme
blastme

Reputation: 429

Need help saving id automatically in laravel

I have just started using laravel version 5.5.13. And I have encountered some problem when doing a one to many relationship table. I had followed this tutorial

https://scotch.io/tutorials/a-guide-to-using-eloquent-orm-in-laravel

When doing it but there was a part where I would need to assign the id manually(bear_id). Is there any way to do it automatically for it? And after assigning the id how do you get the data from it.

Blade.php

For the bear: {{Form::text('name_of_bear, '', ['class' => 'form-control'])}}

For the fish: <input type="checkbox" id="inlineCheckbox1" name="type_of_fish[]" value="Salmon"> Salmon and <input type="checkbox" id="inlineCheckbox1" name="type_of_fish[]" value="Sardine"> Sardine

Bear table:

Schema::create('bears, function (Blueprint $table) {
            $table->increments('id');
            $table->engine = 'InnoDB';  
            $table->string(name); 
            $table->timestamps();
});

Fish table:

Schema::create(fishs, function (Blueprint $table) {
            $table->increments('id');
            $table->engine = 'InnoDB';  
            $table->string(name); 
            $table->integer(bear_id);
            $table->timestamps();
});

Fish model:

namespace App;

use Illuminate\Database\Eloquent\Model;
use Eloquent;


class fish extends Eloquent
{
        protected $fillable = array('name', 'bear_id');

    // DEFINE RELATIONSHIPS 
    public function bears() {
        return $this->belongsTo('App\bear);
    }
}

Bear Model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Eloquent;

class bear extends Eloquent
{
    protected $primaryKey = 'id';
    public function fishs() {
        return $this->hasMany('App\fish,'bear_id');
    }
}

I know there are some other method to do it such as attaching it or associating it but I don't really know how to use it. So would it be possible to show some example for me for referencing?

What I want: 1. For example, 1 bear (bear_id = 1) can have many fish (fish_id = 1 and 2), how do you do this? 2. And how do you get the data from it as my bear_id is 0 (inside database) and don't quite know how to use other methods such as attaching or associate or pivot

Upvotes: 0

Views: 75

Answers (1)

Matey
Matey

Reputation: 1210

Let's say there is a bear_id column in your fish database table and your bear-fish relationship is defined like this:

class Bear extends Model
{
    public function fish()
    {
        return $this->hasMany('App\Fish');
    }
}

Associating fish with the bear can then be done manually like this:

$fish->bear_id = $bear->id;    
$fish->save();

Or you can create the relationship via the relationship method:

$bear->fish()->save($fish);

Upvotes: 1

Related Questions