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
Related
I'm wondering if this is possible. I have 3 models.
Users
TenantPreferances
PropertyAdverts
I'm trying to find out if I can do a query like so.
Find all tenants, whose preferences, match the currently signed in users properties.
The 3 databases are like so
User Model
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('userType');
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
PropertyAdverts
Schema::create('property_adverts', function (Blueprint $table) {
$table->increments('id');
$table->string("photo");
$table->string('address');
$table->string('county');
$table->string('town');
$table->string('type');
$table->string('rent');
$table->string('date');
$table->string('bedrooms');
$table->string('bathrooms');
$table->string('furnished');
$table->longText('description');
$table->integer('user_id'); //Landlord ID
$table->timestamps();
});
Tenant Preferances
Schema::create('tenant_preferances', function (Blueprint $table) {
$table->increments('id');
$table->string('county');
$table->string('type');
$table->string('rent');
$table->string('bedrooms');
$table->string('bathrooms');
$table->boolean('status')->default('0');
$table->integer('user_id'); //Tenant ID
$table->timestamps();
});
Yes, that is possible. You need to dig in on relations. You can then create a function to define the relation on you model:
function propertyAdverts() {
return $this->hasMany(PropertyAdverts::class);
}
You can access the relation from the user model by using $user->propertyAdverts. If you want to eager load them you can do so:
User::with('propertyAdverts')->find(3);
But notice that Laravel does not do a regular join by default. It first fetches all users, and then fetches all propertyAdverts using a single query using a in statement.
How can we make a referenced key and foreign key in laravel by migrations.
Think I have two migration files in database directory in laravel, both of them create a different table in my database.
the first migration creates a table that is for posts which has a column in the name of Id.
the second migration create comments table that has a column in the name of post_id. Now the Id column in posts table is referenced key and the post_id in comments table is foreign key, how can I connect these two columns together?
It would be better to set unsignedInteger for foreign key type
$table->unsignedInteger('category_id')->nullable();
$table->foreign('category_id')
->references('id')
->on('categories')
->onUpdate('cascade')
->onDelete('some action');;
Take the example where you have a users table and a user_address table. A user can have many addresses and an address belongs to a user.
Default user table
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
user_addresses table with user_id as the foreign key
Schema::create('user_addresses', function (Blueprint $table) {
$table->bigIncrements('id'); // by default the primary key is set to unsigned big integer
$table->unsignedBigInteger('user_id'); //associate the address with a user
$table->text('address');
$table->string('city');
$table->string('country');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
After defining the migrations, next step is to define the relationship in their respective model classes
In the User Model, add
public function address(){
return $this->hasMany(UserAddress::class );
}
And in the UserAddress Model, add
public function user(){
return $this->belongsTo(User::class, 'user_id');
}
you use like this.
$table->integer('userId')->unsigned();
$table->foreign('userId')->references('id')->on('users')->onDelete('cascade')->onUpdate('cascade');
If you're trying to create a foreign key constraint for a table that references the 'id' column on a 'users' table for example. For a better developer experience, you can write it in this way:
$table->foreignId('user_id')
->constrained('users')
->onUpdate('cascade')
->onDelete('cascade');
Schema::table('posts', function (Blueprint $table) {
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
});
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.
I'm quite new to programming and am struggling to understand how I should specify the eloquent relationships.
I've created a website where there is an event called a "hangout" and a "join" button which allows users to join the event, thereby attaching their user_id to the hangout_id via a pivot table.
Right now I'm very confused as to how I should/can:
specify the relationships between hangout and users;
for a single hangout, display a list of users attending;
for a single user, display a list of hangouts created; and
for a single user, display a list of hangouts they are attending?
Users can create many hangouts, i.e. hasMany, but when they click "join", they also belongToMany hangouts.
Whilst hangouts can only belong to one user but can have many attendees/users.
Can someone point me in the right direction? This is what I have so far...
User.php
public function hangouts()
{
return $this->hasMany('App\Hangout');
}
public function attending()
{
return $this->belongsToMany('App\Hangout');
}
Hangout.php
public function user()
{
return $this->belongsTo('App\User');
}
public function attendees()
{
return $this->hasMany('App\User');
}
Users Table
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password', 60);
$table->rememberToken();
$table->timestamps();
$table->boolean('admin');
});
}
Hangout Table:
public function up()
{
Schema::create('hangouts', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->string('title');
$table->string('description');
$table->integer('price')->unsigned();
$table->timestamp('published_at');
$table->timestamps();
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
});
Schema::create('hangout_user', function(Blueprint $table)
{
$table->integer('hangout_id')->unsigned()->index();
$table->foreign('hangout_id')->references('id')->on('hangouts')->onDelete('cascade');
$table->integer('user_id')->unsigned()->index();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->timestamps();
});
}
Thanks in advance
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.