in laravel 5.1 can see table column relationships can set-up in 2 ways:
1) defining foreign keys in migration table.
2) defining eloquent relationships in models.
i have read documentations , still confused on following:
do need use both or 1 needed?
is wrong use both @ same time? or make redundant or cause conflicts?
what benefit of using eloquent relationships without mentioning foreign keys in migration column?
what difference?
these codes have now. still unclear me if need remove foreign keys have set-up in migration file.
migration:
public function up() { schema::create('apps', function (blueprint $table) { $table->increments('id'); $table->string('app_name'); $table->string('app_alias'); $table->timestamps(); $table->engine = 'innodb'; }); // second migration table schema::create('app_roles', function (blueprint $table) { $table->increments('id'); $table->integer('app_id')->unsigned()->index(); $table->integer('user_id')->unsigned()->index(); $table->integer('role_id')->unsigned()->index(); $table->engine = 'innodb'; $table->unique(array('app_id', 'user_id')); $table->foreign('app_id') ->references('id') ->on('apps') ->ondelete('cascade'); $table->foreign('user_id') ->references('id') ->on('users') ->ondelete('cascade'); $table->foreign('role_id') ->references('id') ->on('roles') ->ondelete('cascade'); }); } model eloquent relationships:
// app model class app extends model { public function approles() { return $this->hasmany('app\models\approle'); } } // approle model class approle extends model { public function app() { return $this->belongsto('app\models\app'); } public function user() { return $this->belongsto('app\user'); } public function role() { return $this->belongsto('app\models\role'); } } // user model class user extends model implements authenticatablecontract, canresetpasswordcontract { ..... public function approle() { return $this->belongstomany('app\models\approle'); } } // role model class role extends entrustrole { public function approle() { return $this->hasmany('app\models\approle'); } } can me understand please?
both go hand in hand. 1 in-complete without other one. if want work relations perfectly, need define both things.
if have defined foreign key in migration file, relation work in case write raw query. won't work on models; since, haven't written relations in models.
so, write hasmany in 1 of models, , corresponding function in other model, model knows it, , query things through model in database.
also note if have defined relations through hasmany , belongsto in models, haven't provided foreign key in table of model belongsto other table, relations won't work.
in short, both equally compulsory.
Comments
Post a Comment