Laravel 3 way pivot when two column come from same id - laravel-5

How can i set up this, i'm trying to build a student and teacher lesson schedule, here is my code.
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->text('photo_url')->nullable();
$table->string('firstname');
$table->string('lastname');
$table->string('username')->unique()->nullable();
$table->date('date_of_birth');
$table->string('email')->unique();
$table->string('password');
$table->timeTz('timezone');
$table->integer('is_active')->default(0);
$table->tinyInteger('verified')->default(0);
$table->string('email_token')->nullable();
$table->text('address');
$table->string('district');
$table->rememberToken();
$table->timestamps();
});
And then for the lesson schedules
Schema::create('lessons', function (Blueprint $table) {
$table->increments('id');
$table->integer('status'); //0 - not started, 1 - completed, 2 - no show
$table->dateTime('start_at');
$table->dateTime('end_at');
$table->dateTime('started_at');
$table->dateTime('ended_at');
$table->string('unique_id')->unique();
$table->integer('teacher_id')->unsigned();
$table->foreign('teacher_id')
->references('id')->on('users')
->onUpdate('cascade')
->onDelete('cascade');
$table->integer('student_id')->unsigned();
$table->foreign('student_id')
->references('id')->on('users')
->onUpdate('cascade')
->onDelete('cascade');
$table->integer('completed');
$table->timestamps();
});
if i want to display my data on the view for this. How do i add the relations to the various models and how do i display them to view.
I believe this is a belongsToMany relations
Pleas help!
how do i do this?
Not sure if i clear enough

I think that using a pivot may restrict you somewhat, and make things more complicated.
Instead, why not create a model such as Schedule?
Student has many Schedule
Schedule belongs to a Student
Schedule belongs to a Teacher
Schedule belongs to a Lesson
Student has many Lesson through Schedule
This also allows you to expand on this further since you're dealing with a model specifically for the purpose.

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

Laravel combine multiple collections into one query

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.

Laravel relationships for sports fixtures

So, I am creating a results website for boxing, I am trying to get a boxers past results, but am struggling with relationships...
For example, a boxer can have many events (a fight), and have 1 result (a win, draw or loss), and 1 opponent. I am trying to display all of the boxers results, with the opponents information
So, I have an event with the structure (can add a relationship id if needed)
Schema::create('events', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->date('date');
$table->string('location');
$table->timestamps();
$table->softDeletes();
});
I have a boxer table
Schema::create('boxers', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('status');
$table->string('division');
$table->string('stance');
$table->date('dob');
$table->integer('height');
$table->string('nationality');
$table->string('residence');
$table->string('birthplace');
$table->timestamps();
$table->softDeletes();
});
and the results
Schema::create('results', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id');
$table->integer('event_id');
$table->string('result');
$table->timestamps();
$table->softDeletes();
});
What would I need to add and change to get a relationship to work correctly?
Events typically hasMany fights (many fights on a card), each fight hasMany (two) athletes. So your fight/athlete relationship would be many-to-many (fighters have many fights throughout their career). You'll create a pivot table athletes_fights which will have fight_id and athlete_id columns. Additionally, this pivot table could have a winner_id and a draw column. Draw could default to 0, 1 if the fight is a draw. It could also have win_method (could even create another table for this and make it win_method_id), win_round, win_time.
Check out the relationships section in the Laravel docs, if you haven't already.
So your model would be..
Event
Fight
Athlete

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