Migration Foreign Key Vs Eloquent Relationships in Laravel - php

In Laravel 5.1 I can see that table column relationships can be set-up in 2 ways:
1) Defining Foreign Keys in the Migration table.
2) Defining the Eloquent relationships in the Models.
I have read the documentations and I am still confused on the following:
Do I need to use both or only 1 is needed?
Is it wrong to use both at the same time? Or does it make it
redundant or cause conflicts?
What is the benefit of using Eloquent relationships without mentioning the
Foreign keys in migration column?
What is the difference?
These are the codes I have now. Its still unclear to me if I need to remove the foreign keys I have set-up in my 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';
});
// This is the 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 with 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 someone help me understand this please?

Both go hand in hand. One is in-complete without the other one. If you want your relations to work properly, you need to define both of these things.
If you have just defined the foreign key in a migration file, the relation would work just in case you write a raw query. It won't work on your models since, you haven't written anything about relations in your models.
So, as soon as you write hasMany in one of your models, and corresponding function in the other model, only then your models know about each other, and then you can successfully query things through your model as well as in your database.
Also note that if you have properly defined relations through hasMany and belongsTo in your models, but haven't provided foreign key in the table of the model who belongsTo other table, your relations won't work.
In short, both are equally compulsory.

Eloquent assumes the foreign key of the relationship based on the model name. In this case, the App model is automatically assumed to have an app_id foreign key, so in your migrations you do not need to specify:
$table->foreign('app_id')
->references('id')
->on('apps')
->onDelete('cascade');
Documentation

Related

Laravel Eloquent where statement returns no attributes

So from my previous post, I was advised to start using Eloquent models, which I did.
My end goal, is to print out specific gifts, that belongs to that specific box.
Migrations:
gift_items:
public function up()
{
Schema::create('gift_items', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->float('unit_price');
$table->integer('units_owned');
});
}
gift_campaigns:
public function up()
{
Schema::create('gift_campaigns', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->foreignId('user_foreignK')->constrained('users');
$table->integer('gift_item_count')->nullable();
$table->string('status');
$table->date('dispatch_date');
$table->date('delivery_date');
});
}
Pivot table:
public function up()
{
Schema::create('campaigns_gifts', function (Blueprint $table) {
$table->foreignId('gift_id')->constrained('gift_items');
$table->foreignId('campaign_id')->constrained('gift_campaigns');
});
}
Controller:
function box($id){
$data = Campaign::with('gifts')->where('id', $id)->get();
return view('DBqueries.boxView', ['data'=>$data]);
}
Error that I receive using this way:
Seems like the updated version is trying to call the gift_campaigns table id, instead of the pivots table campaign_id.
Once again, I need that Request $id would match the pivots table campaign_id, and print out all of the gifts that this specific id holds
First of all as I sense the campaigns_gifts is a pivot table for campaigns and gifts having a Many-to-Many relation. You are doing it completely against the conventions of Laravel.
You generally do not use a Model for pivot table.
You generally do not fetch data from the pivot table directly. Instead use the relation on one of the related Models.
Note: Laravel does allow a Model for a Pivot, and you can query the pivot table directly, just check the documentation.
The correct way:
Pivot
Make a pivot table (that you already have) with column gift_id and campaign_id. i.e., the convention for naming keys as [table_name_singular]_[primary_key_on_table]
Model
One each model, define relationship for the other data as:
Gift.php Model:
public function campaign() {
return $this->belongsToMany(Campaign::class, 'campaign_gift');
}
Campaign.php Model:
public function gifts() {
return $this->belongsToMany(Gift::class,'campaign_gift');
}
since gift have a hasMany relation, the gifts table must contain a foreign key to campaigns table named campaign_id (same as the one on pivot).
Controller
Now in your controller:
function box($id){
$data = Campaign::where('id',$id)->with('gifts')->get();
return view('DBqueries.boxView', ['data'=>$data]);
}
You don't need to tell Laravel which columns, tables etc are you referring to, as long as you follow the conventions, Laravel will magically do things that otherwise would have been much more painful.

Track multiple booleans with laravel's many to many relationship

My migration code for relation table:
Schema::create('users_games', function (Blueprint $table) {
$table->bigInteger('user_id')->unsigned();
$table->index('user_id');
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
$table->bigInteger('game_id')->unsigned();
$table->index('game_id');
$table->foreign('game_id')
->references('id')
->on('games')
->onDelete('cascade');
$table->boolean('liked')->default(false);
$table->boolean('played')->default(false);
$table->boolean('wishlisted')->default(false);
// composite primary key
$table->primary(['user_id', 'game_id']);
});
basically a user can mark a game like, played or add to wishlist. I want to track all those actions in the same table.
I want to represent the same in Elloquent Model for users and games, however I dont know how to. can anyone tell me how these properties inside respective models should look like please?
in your User Model:
<?php
namespace App\Models;
class User extends Model
{
public function games()
{
return $this->hasMany(Game::class);
}
}
in your Game model:
<?php
namespace App\Models;
class Game extends Model
{
public function user()
{
return $this->belongsToMany(User::class);
}
}
then you can get the value of played property from the first game in the Eloquent like this:
$user = auth->user()
$user->games->first()->liked

Seeding Relationship one to many in Laravel

I need to seed a relationship in Laravel, where each user has many devices
The User model
public function devices()
{
return $this->hasMany(Device::class);
}
The Device model
public function users()
{
return $this->belongsTo(User::class);
}
}
The device_user table
Schema::create('device_user', function (Blueprint $table) {
$table->increments('id');
$table->integer('device_id')->unsigned()->index();
$table->foreign('device_id')->references('id')->on('devices')->onDelete('cascade');
$table->integer('user_id')->unsigned()->index();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->timestamps();
});
The seeder
factory(App\Device::class, 20)->create()->each(function(App\Device $device) {
$device->users()->attach([
rand(1,5),
rand(6,15),
rand(16,20),
]);
});
But, when I run the migration with seeder, I get this message
Call to undefined method Illuminate\Database\Query\Builder::attach()
Please, help
attach for many to many relationships, you don't need device_user table for one to many relationship, in one to many you should create a column with name user_id in device table and just it. after that you can insert data in device table with user_id. and get user relationship with
Device::user()->get();

How to use many to many polymorphic relation in Laravel 5.2

I am reading laravel 5.2 docs to implement many to many polymorphic relation in my Laravel Application.
I have Many models like Blog, Question, Photo etc and I want to have Tagging system for all of them.
I have created Tag table with following schema
Schema::create('tags', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('slug')->unique();
$table->timestamps();
});
Below is pivot table schema. Pivot table name is entity_tags
Schema::create('entity_tags', function (Blueprint $table) {
$table->increments('id');
$table->integer('tag_id')->unsigned();;
$table->integer('taggable_id')->unsigned();
$table->string('taggable_type');
$table->timestamps();
$table->index('tag_id');
$table->index('taggable_id');
$table->index('taggable_type');
});
This is the relationship defined in Tag model for Question model
public function questions()
{
return $this->belongsToMany('App\Question', 'entity_tags', 'tag_id', 'taggable_id');
}
And the following relation is defined in Question Model
public function tags()
{
return $this->belongsToMany('App\Tag', 'entity_tags', 'taggable_id', 'tag_id');
}
Now I want to define Many to Many Polymorphic relationship as defined in Laravel 5.2.
My Question are
how I can define them?
Should I remove the Many to Many
relationship and only define Many to Many polymorphic relationship ?
If yes, then how to manage custom pivot table name ?
Also is it required to suffix column name with word able that are part of
polymorphic relationship ?
Use return $this->morphToMany() instead of belongsToMany, and in the Tag model, write 3 methods with return $this->morphedByMany() for the reverse relationship.
You only need polymorphic definitions, no need for the many to many normal ones. The name of the pivot table is with 'able' at the end by the default convention but you can name it anything you want.
no, you don't have to have a word with 'able' at the end, it's just a way to define that it's something more general, you can name it anything you want.
Naming is based on some default convention by Laravel.
Update:
You have the following pivot table schema:
Schema::create('entity_tags', function (Blueprint $table) {
$table->increments('id');
$table->integer('tag_id')->unsigned();;
$table->integer('entity_id')->unsigned();
$table->string('entity_type');
$table->timestamps();
$table->index('tag_id');
$table->index('entity_id');
$table->index('entity_type');
});
and the tags table:
Schema::create('tags', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('slug')->unique();
$table->timestamps();
});
So you want to create the relationships for blog, video and question tables / models:
Tag.php Model:
public function questions()
{
return $this->morphedByMany('App\Question', 'entity', 'entity_tags');
}
public function blogs()
{
return $this->morphedByMany('App\Blog', 'entity', 'entity_tags');
}
public function videos()
{
return $this->morphedByMany('App\Video', 'entity', 'entity_tags');
}
Question.php / Blog.php / Video.php
public function tags()
{
return $this->morphToMany('App\Tag', 'entity', 'entity_tags');
}

Laravel 4 - Select related models

I have following table
Schema::create('jokes_categories', function(Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('is_active');
$table->timestamps();
});
Schema::create('jokes', function(Blueprint $table) {
$table->increments('id');
$table->string('content', 200)->unique();;
$table->enum('is_active', array('Y', 'N'));
$table->integer('category_id')->unsigned();
$table->foreign('category_id')->references('id')->on('jokes_categories');
$table->timestamps();
});
In the jokes table category_id is a foreign key and it has a one-to-many relationship with jokes_categories
In the model I have the following:
class Joke extends \Eloquent {
public static $rules = array();
// Don't forget to fill this array
protected $fillable = array();
public function JokesCategory(){
return $this->belongsTo('JokesCategory');
}
}
In the controller I have the following:
$jokes = Joke::all();
But it does not pull through joke_categories.name (I was under the impression that the model definition will directly help to pull related models)
What could be the solution?
Your query is just on the Joke table.
You could eagerload the categories ie.
$jokes = Joke::with('JokesCategory')->get();
See docs: http://laravel.com/docs/eloquent#eager-loading
The convention is actually camel case instead of pascal case, otherwise Laravel doesn't seem to automatically load the relationships. I made the same mistake and couldn't figure out why my relationships where not loading automatically.
public function jokesCategory()

Categories