One-To-Many Relation with Pivot Table - laravel

I have 2 tables Manufacturers and Suppliers ,and they have Many-to-Many relation
Schema::create('manufacturers', function (Blueprint $table) {
$table->increments('id');
$table->string('name')->unique();
$table->timestamps();
});
Schema::create('suppliers', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('location');
$table->timestamps();
​ });
so i created a pivot table called "manufacturer_supplier" and it works fine.
Schema::create('manufacturer_supplier', function (Blueprint $table) {
$table->increments('id');
$table->integer('manufacturer_id')->unsigned()->index();
$table->integer('supplier_id')->unsigned()->index();
$table->timestamps();
$table->foreign('manufacturer_id')->references('id')->on('manufacturers')->onDelete('cascade');
$table->foreign('supplier_id')->references('id')->on('suppliers')->onDelete('cascade');
});
My confusion comes from adding a new table "devices"
Schema::create('devices', function (Blueprint $table) {
$table->increments('id');
$table->string('serial')->unique();
$table->string('name');
​$table->integer('supplier_id')->unsigned()->nullable();
$table->integer('manufacturer_id')->unsigned()->nullable();
$table->text('notes')->nullable();
$table->timestamps();
$table->foreign('supplier_id')->references('id')->on('suppliers')->onDelete('cascade');
$table->foreign('manufacturer_id')->references('id')->on('manufacturers')->onDelete('cascade');
});
where i want to have a one-to-many relation with each of suppliers and manufacturers , so i would have a select list of manufacturers and then populate the next list from with suppliers from Pivot table that relate to the selected manufacturer.
currently my "device"​ model has the following relations which it relate them to the original table not the pivot so it doesn't work
//5
public function manufacturer(){
return $this->belongsTo('App\Manufacturer');
}
//6
public function supplier(){
return $this->belongsTo('App\Supplier');
}
I haven't done that before so i'm curious to know what will be the best fix for this to work.
Thanks a lot ,

If you want all suppliers associated with a single manufacturer you could get them using the many-to-many relation.
$suppliersList = $supplier->manufacturer()->suppliers();
howerver I don't understand why a device should be associated with a single supplier .... but that's up to you.

Related

Laravel Eloquent: Multiple Foreign Keys from One Primary Key

I am in-progress to create a project in Laravel.
I have two Database Table, which is created by migrations:
I want to setup multiple foreign key in database schema.
Table User
Schema::create('tr_users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('email');
$table->timestamp('email_verified_at')->nullable();
$table->rememberToken();
$table->string('password');
$table->unsignedBigInteger('departement_id')->nullable();
$table->foreign('departement_id')
->references('id_departement')->on('tr_departements')
->onUpdate('cascade')
->onDelete('cascade');
});
Table Departrements
Schema::create('tr_departements', function (Blueprint $table) {
$table->bigIncrements('id_departement');
$table->string('name');
$table->timestamps();
$table->unsignedBigInteger('created_by')->nullable();
$table->foreign('created_by')
->references('id')->on('tr_users')
->onDelete('cascade');
$table->unsignedBigInteger('updated_by')->nullable();
$table->foreign('updated_by')
->references('id')->on('tr_users')
->onDelete('cascade');
});
What I want to know is how to describe relation in Models?
Edit:
My plan to use this relation is every users is belongs to departement, and any departement has many users, and every users has only one departement
If you are seeking One-to-One relationship from user to department then relation would be like this:
In your User model code would be like this:
public function department()
{
return $this->hasOne('App\Department');
}
And in your department model:
public function user()
{
return $this->belongsTo('App\User');
}
For multiple relationship you can refer laravel documentation

Has Many Through where the middle table has both forain keys in laravel 5.6

I need to make a HasManyThough relation where the middle Model holds the foreign keys of both Models.
Here is detail:
Migrations:
Schema::create('carriers', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
});
Schema::create('shipping_zones', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
});
Schema::create('shipping_rates', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->integer('shipping_zone_id')->unsigned()->index();
$table->integer('carrier_id')->unsigned()->index();
$table->decimal('rate', 20, 6);
});
Now I need something like
$carrier->shippingZone()
Is there any easy way to get this?
As per your migrations you need Many To Many relation rather than the HasManyThough relation.
Carrier.php
public function shippingZones()
{
return $this->belongsToMany('App\ShippingZone', 'shipping_rates);
}
You can access all shipping zones related to the carrier using, $carrier->shippingZones.
If you need to chain the query you can use $shippingZones = $carrier->shippingZones()->orderBy('id')->get(); here
If you need to use HasManyThough you would have to change the migrations. here

how can I use event and listener by laravel to handle the booking?

I have rooms in hospitals. Each room has beds with numbers. I want to assign beds to patients. How can I handle this in an easy way:
rooms migration:
Schema::create('rooms', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->integer('floor');
$table->text('description');
$table->timestamps();
});
beds migration:
Schema::create('beds', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('quality');
$table->string('charge');
$table->integer('room_id')->unsigned();;
$table->foreign('room_id')->references('id')->on('rooms')
->onUpdate('cascade')->onDelete('cascade');
$table->boolean('status');
$table->timestamps();
});
reservations migration:
Schema::create('reservations', function (Blueprint $table) {
$table->increments('id');
$table->date('date_in');
$table->date('date_out');
$table->boolean('status');
$table->integer('patient_id')->unsigned();
$table->foreign('patient_id')->references('id')->on('patients');
$table->integer('bed_id')->unsigned();
$table->foreign('bed_id')->references('id')->on('beds');
$table->timestamps();
});
How can I check for available beds? Get the available beds? Be sure the bed is available. How can I use events and listeners to make the whole thing work?
pluck() retrieve a Collection containing the values of a single column.
Here, it retrieves a Collection of reservation bed_id:
$reserved = Reservation::pluck('bed_id)->all();
The whereNotIn method verifies that the given column's value is not contained in the given array:
$bed_available = Bed::whereNotIn('id' , $reserved)->get();
This query gives you all the bed whose id is not available in that collection $reserved , which i think is your requirement .

Laravel: How do I model this Article/Category scenario?

I have a scenario with Articles and Categories where each article can have only one category through a CategoryGroup.
This means the article can have more than one category but only one unique category from each category_group. Or, to put it another way, the article can have only one category from each category_group.
Do I model this scenario at the level of relationships? Or is this a matter of using custom validation?
This seems like a hasOneThrough scenario but this doesn't exist. So what's the workaround?
I have tried a many-to-many relationship between articles and categories but how do I constrain the article from having more than one of each category type while attaching categories to single articles?
Schema::create('articles', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->text('body');
$table->string('slug');
$table->timestamps();
});
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->text('description');
$table->string('slug');
$table->string('handle');
$table->integer('category_group_id')->index()->nullable();
$table->timestamps();
});
Schema::create('article_category', function (Blueprint $table) {
$table->integer('article_id')->unsigned();
$table->integer('category_id')->unsigned();
$table->primary(['article_id', 'category_id']);
$table->timestamps();
});

How to set up Eloquent relationships to work with a 3-way pivot table

I have a 3 way pivot table that ties a role to a user for a specific organization. Here's how the relevant tables are set up:
//users table
Schema::create('users', function($table)
{
$table->engine = 'InnoDB';
$table->increments('id');
$table->string('username', 30)->index();
//more (irrelevant) fields here
$table->timestamps();
});
//roles table
Schema::create('roles', function(Blueprint $table)
{
$table->engine = 'InnoDB';
$table->increments('id');
$table->string('name', 100)->index();
$table->string('description', 255)->nullable();
$table->timestamps();
});
//organizations table
Schema::create('organizations', function(Blueprint $table)
{
$table->engine = 'InnoDB';
$table->increments('id');
$table->string('name', 255);
$table->string('slug', 100);
$table->text('description');
$table->timestamps();
});
//organization user role table
Schema::create('organization_user_role', function(Blueprint $table)
{
$table->engine = 'InnoDB';
$table->increments('id');
$table->integer('role_id')->unsigned()->index();
$table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
$table->integer('user_id')->unsigned()->index();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->integer('organization_id')->unsigned()->index();
$table->foreign('organization_id')->references('id')->on('organizations')->onDelete('cascade');
$table->timestamps();
});
Each user can belong to one or more organizations, with one or more roles. Roles are tied to both a user and an organization simultaneously. That is to say, a user must have a role in an organization in order to be associated with it.
This doesn't seem to fit the mold of the traditional many-to-many relationship pivot-table that works so well out-of-the-box with Eloquent. Can Eloquent handle this type of relationship, or do I need a new model dedicated to handling the relationship? Can someone please show me what the User, Organization, and Role models would look like to tie the 3-way pivot table relationships together with Eloquent?
Check this out: http://github.com/jarektkaczyk/Eloquent-triple-pivot
It works, however I wouldn't call it complete solution. Still you can build yours on top of that.

Resources