Support the ongoing development of Laravel.io →
Database Eloquent Forms
Last updated 1 year ago.
0

Before attending the above, could I just clarify something please. I am trying to understand foreign keys. When I create a migration, should I do

$table->foreign('seathunter_id')->references('id')->on('seat_hunter')->onDelete('cascade')->onUpdate('cascade');

Or should I be doing this in the Model instead?

public function seatHunter() {
        return $this->belongsTo('seat_hunter');
 }

So my real question is, is it one or the other?

Thanks

0

Both. With migrations you create the database tables (with the necessary foreigns keys). In the model you have to add the relationships if you want to access them.

Example: In my migrations:

Schema::create('regions', function($table) {
	$table->increments('id');
	$table->integer('languageId')->unsigned();
	$table->foreign('languageId')->references('id')->on('languages');
	$table->integer('countryId')->unsigned();
	$table->foreign('countryId')->references('id')->on('countries');
	$table->integer('sequence')->unsigned();
});

In my model:

<?php namespace Models;

class Region extends \Entity {

    protected $table = 'regions';
    public $timestamps = false;
	
    public function language()
    {
        return $this->belongsTo('\Models\Language', 'languageId');
    }
	
    public function country()
    {
        return $this->belongsTo('\Models\Country', 'countryId');
    }
}
0

Sign in to participate in this thread!

Eventy

Your banner here too?

nick2price nick2price Joined 20 Jan 2015

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.