Relation belongs to table with double primary key in Laravel - laravel

I need to store in a database the weekly hour of an user. For example, the user A work at monday from 8:00am to 17:00pm, on tuesday from 9:00am to 11:00am ecc...
For do this I created two table:
Users (id, username, ecc...)
Hours (user_id, day, start, end) with "user_id" and "day" as primary key.
Instead of create another table called Days with only 7 records (one for each day).
My problem is to define the relation with laravel, indeed if I use three tables I can use Many to Many relation, but if I use this form how I can specific that "day" column is a key?

I suggest following table structure of Hours
id (primary key, auto-increment)
user_id
day (NOT primary key, values from 1-7)
start
end
Then you can add a UNIQUE index over the combination of user_id and day.
SQL: ALTER TABLE hours ADD UNIQUE unique_user_day (user_id, day);
Laravel schema builder (migration): $table->unique(array('user_id', 'day'));
After that you just need a normal relation. Nothing fancy at all.
public function hours(){
return $this->hasMany('Hours');
}
This is how you get all hours
$hours = Users::find(1)->hours;
And then, when you need a specific day, add a where statement
$tuesday = Users::find(1)->hours()->where('day', 2)->get();
Or for a nicer syntax you could a function to your users model
public function day($number){
return $this->hours()->where('day', $number)->get();
}
$tuesday = Users::find(1)->day(2);
You could even work with constants for the weekdays...

Related

Pivot table but not using table id

Is it possible to make a Pivot Table without using table id?
users
id
biometric_id
first_name
last_name
attendances
id
biometric_id
date
emp_in
emp_out
user_attendances
user_id
attendances_biometrics_id
I wanted to ask if this is available to link it like this? Because I need to show the attendance of the user that has his biometrics.
If it is possible, how?
If attendances.biometric_id has a unique constraint on it then there should be no reason why you cannot use it as a foreign key constraint.
Assuming your tables have been setup properly with foreign key constraints, your user model would probably have something like this:
public function attendances() {
return $this->belongsToMany('App\Attendances', 'user_attendances', 'user_id', 'attendances_biometrics_id');
}

Clustering order does not work with compound partition key

With the following table definition:
CREATE TABLE device_by_create_date (
year int,
comm_nr text,
created_at timestamp,
PRIMARY KEY ((year, comm_nr), created_at)
) WITH CLUSTERING ORDER BY (created_at DESC)
Comm_nr is a unique identifier.
I would expect to see data ordered by created_at column, which is not the case when I add data.
Example entries:
Table CQL:
How can I issue select * from table; queries, which return data ordered by the created_at row?
TLDR: You need to create a new table.
Your partition key is (year, comm_nr). You're created_at key is ordered but it is ordered WITHIN that partition key. A query where SELECT * FROM table WHERE year=x AND comm_nr=y; will be ordered by created_at.
Additionally if instead of (year, comm_nr), created_at your key was instead year, comm_r, created_at even if your create table syntax only specifiied created_at as the having a clustering order, it would be created as WITH CLUSTERING ORDER BY (comm_nr DESC, created_at DESC). Data is sorted within SSTables by key from left to right.
The way to do this in true nosql fashion is to create a separate table where your key is instead year, created_at, comm_nr. You would write to both on user creation, but if you needed the answer for who created their account first you would instead query the new table.

Save on different tables using Eloquent Laravel Relationships

Hi I have 3 tables "temp_quotes", "quotes" and "quote_items"
Every quote generated goes to the "temp_quotes" table at first.
At the end of my multi-step form I need the following:
1- Receive all the quotes from the "temp_quotes" table, send it to the "quote_items" table and delete it from the "temp_quotes" table
2- Generate a new entry in the "quotes" table referencing the "users" table and
the "quote_items" table
Here is all the data and how needs to be save/removed on the tables:
temp_quotes Table
ID
BRAND
MODEL
YEAR
quotes Table:
ID
USER_ID
QUOTE_ID
quote_items Table:
ID
QUOTE_ID
BRAND
MODEL
YEAR
Any help will be appreciated.

Laravel / Eloquent -- Lookup Table Issue

I have 3 tables that I am trying to work through and am having a hard time connecting them via Eloquent joins.
Character Table
profileID (PK)
Character Gear Table
profileId (PK)
qualityId (FK)
Quality Lookup Table
id (PK)
name
I am able to access the Character Gear Lookup with the following in my Character Model:
public function gear()
{
return $this->hasMany('App\Models\CharacterGear', 'profileId')->where('gearSet', '=', '0');
}
How do I get the lookup to work so that I can get the quality name from the Quality Lookup table to tie in to the gear() shown above?
Please let me know if you need any further information!
Figured it out. Eloquent has Nested Relationships and I didn't know that.

Soft delete on a intermediate table for many-to-many relationship

How do I set soft delete on an intermediate table which is connecting two different types of entities? I've added deleted_at column, but the docs say that I need to put this into the model:
protected $softDelete = true;
Of course, I don't have a model for an intermediate table.
Any idea?
You can put a constraint on the Eager Load:
public function groups()
{
return $this
->belongsToMany('Group')
->whereNull('group_user.deleted_at') // Table `group_user` has column `deleted_at`
->withTimestamps(); // Table `group_user` has columns: `created_at`, `updated_at`
}
Instead of HARD deleting the relationship using:
User::find(1)->groups()->detach();
You should use something like this to SOFT delete instead:
DB::table('group_user')
->where('user_id', $user_id)
->where('group_id', $group_id)
->update(array('deleted_at' => DB::raw('NOW()')));
You could also use Laravel's Eloquent BelongsToMany method updateExistingPivot.
$model->relation->updateExistingPivot($relatedId, ['deleted_at' => Carbon\Carbon::now()]);
So to use #RonaldHulshof examples you have a User model with a groups relationship which is a belongsToMany relationship.
public function groups() {
return $this->belongsToMany(Group::class)->whereNull('groups_users.deleted_at')->withTimestamps();
}
Then in order to soft delete the pivot table entry you would do the following.
$user->groups()->updateExistingPivot($groupId, ['deleted_at' => Carbon\Carbon::now()]);
As far as I understand it; an intermediate table is simply a length of string attaching one tables record to a record in another table and as such it does not require a soft delete method.
To explain, imagine you have a Users table and a Groups table, each user can have more than one Group and each Group can belong to more than one User. Your pivot table may be User_Group or something like that and it simply contains two columns user_id and group_id.
Your User table and Group table should have a deleted_at column for soft deletes, so when you "delete" say a Group, that group association will not appear in $User->Groups() while the pivot table row has remained unaffected. If you then restore that deleted Group, it will once again appear in $User->Groups().
The pivot table row should only be affected if that group record is hard deleted, in which case the pivot rows should also be hard deleted.
Now I have explained why I do not believe you need to add soft delete to a pivot table; is there still a reason why you need this behavior?

Resources