Jaikangam
1 year ago

Inserting values into foreign key table and primary key table

Posted 1 year ago by Jaikangam

I have two tables and i have to insert values into these two tables such that a record in primary table is associated with several records in foreign key table. Pls help me.god bless you

class CreateThievesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('thieves', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('thieves');
    }
}

Another Table here

class CreateCarsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('cars', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');

            $table->integer('thief_id')->unsigned()->index()->nullable();
            $table->foreign('thief_id')->references('id')->on('thieves');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('cars');
    }
}

Assume i have already inserted the value in the thief table now i want to insert Cars table but its getting me saying car undefine.

On the Car Controller

``` public function store(Request $request) {
    $car->thief()->associate($thief)->save();
}

Please sign in or create an account to participate in this conversation.