I have this two tables a User Table and the Attendance table, Here is what I want to do:
While inserting a User on the User table, the Attendance table will also be updated (the user_id of the User Table will be Inserted to the Attendance Table as a foreign key), the Primary key of my User table is Auto Increment, that's why I can't insert it manually to the Attendance Table, what should I do? Is there any cheat in laravel that can do this easily?
Here is my Controller for Register
public function register()
{
$myemployee=Employee::all();
return View::make('registration',compact('myemployee'));
}
public function registerEmp()
{
$input = Input::all();
$command = new Employee;
$command->firstname=$input['firstname'];
$command->lastname=$input['lastname'];
$command->position=$input['position'];
$command->save();
return Redirect::action('EmployeesController#register');
}
Here is my Migration
public function up()
{
Schema::create('employees',function($table)
{
$table->increments('id');
$table->text('firstname');
$table->text('lastname');
$table->text('position');
$table->timestamps();
});
public function up()
{
Schema::create('attendances', function(Blueprint $table)
{
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('employees');
$table->timestamp('intime');
$table->timestamp('offtime');
});
}
Employee.php file
<?php
class Employee extends Eloquent
{
}
?>
You can get the last inserted ID in users table by assigning the return value of User::create(), which is a static Illuminate\Database\Eloquent\Model, to a variable, then use that variable to insert user_id in your attendances table.
Here is an example:
public function registerEmp() {
$input = Input::all();
// Create an employee.
$employee = Employee::create($input);
// Create an attendance entry as well.
Attendance::create([
'user_id'=>$employee->id,
// other columns...
]);
return Redirect::action('EmployeesController#register');}
Related
I have a films table which contains a many to many relation e.g AgeRatings with a pivot table called film_age_rating which contains a film_id as a foreign key I have this with 3 other relations too.
Right now my app has no functionality to make a deletion request to remove a film, so right now I hard delete rows in the films DB table. When I delete a film from the films table it deletes items, but the data within the pivot table remains unchanged which I don't want to happen.
films_table
public function up()
{
Schema::create('films', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->string('name')->nullable();
}
film_age_rating
public function up()
{
Schema::create('film_age_ratings', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('age_rating_id');
$table->uuid('film_id');
$table->timestamps();
});
}
Film Model
public function ageRatings(): BelongsToMany
{
return $this->belongsToMany(
AgeRatings::class,
'film_age_rating',
'film_id',
'age_rating_id'
);
}
Age Rating Model
public function film(): BelongsToMany
{
return $this->belongsToMany(
Film::class,
'film_age_rating',
'age_rating_id',
'film_id'
);
}
I know an option is to add an onDelete cascade to the pivot tables, but that will require lots of migration tables. Is there another way to tackle this without adding a DELETE request for now or is adding the cascade the only option?
Could you please advise me on the most efficient option?
The only way I can imagine is to use softDeletes
On this way, there will be only one query to delete a film, and it will be a logical delete.
You can delete data using the sync() method. It releases the relation from the pivot table. I assuming that you want to delete a film. So this is a sample method in your controller.
public function deleteFilm($id)
{
$film = Film::find($id);
$film->ageRatings()->sync([]);
$film->delete();
}
Problem: I'm trying to query a PeopleType to find all the courses where a person isn't associated.
I have 4 tables
People
PeopleTypes
Courses
People_Courses
PeopleType_Courses
I have the following relationships
PERSON MODEL
public function getPeopleType() {
return $this->belongsTo('App\PeopleType','type_id');
}
public function getCourses() {
return $this->belpngsToMany('App\Course','People_Courses','person_id','course_id');
}
PEOPLE_TYPE MODEL
public function getPeople() {
return $this->hasMany('App\Person','type_id');
}
public function getCourses() {
return $this->belpngsToMany('App\Course','PeopleType_Courses','people_type_id','course_id');
}
My attempt:
$peopleType = \App\PeopleType::FindOrFail(1);
$courses = $peopleType->getCourses()->whereNotIn('id', function($q) use($person) {
$q->select('course_id')
->from('People_Courses')
->where('person_id', $person->id);
})->get();
My response:
Integrity constraint violation: 1052 Column 'id' in IN/ALL/ANY
subquery is ambiguous
People Courses Table Schematic
Schema::create('People_Courses', function (Blueprint $table) {
$table->increments('id');
$table->integer('course_id');
$table->integer('person_id');
);
PeopleType_Courses Table Schematic
Schema::create('PeopleType_Courses', function (Blueprint $table) {
$table->increments('id');
$table->integer('course_id');
$table->integer('people_type_id');
);
When you're working on relations that have similar column name being selected in the query you need to resolve the ambiguity by specifying the table name with the column. e.g:
$peopleType->getCourses()->whereNotIn('courses.id', function($q)... //courses.id
I am working a E-learning website.
I made students, teachers, courses and class_rooms tables in my database.
The plan is to enter a classroom from dashboard then make a new classroom connected to 1 teacher, 1 course and many students.
I can insert teacher and course by ID , but what about the students?
I tried but failed to make another table and connect everything.
You should create pivot table kind
class_room_student. Here you will store class_room ID and student ID.
And use relation many to many
/**
* In ClassRoom Model (getting students of class)
*/
public function students()
{
return $this->belongsToMany(Student::class);
}
/**
* In Student Model (getting classes of one student)
*/
public function classes()
{
return $this->belongsToMany(ClassRoom::class);
}
Don't forget about 'pivot table', 'foreign_key', 'other_key' if needed.
Migration
public function up()
{
Schema::create('class_room_student', function (Blueprint $table) {
$table->integer('student_id')->unsigned();
$table->foreign('student_id')->references('id')->on('students')->onDelete('cascade');
$table->integer('class_room_id')->unsigned();
$table->foreign('class_room_id')->references('id')->on('class_rooms')->onDelete('cascade');
$table->primary(['student_id', 'class_room_id']);
});
}
public function down()
{
Schema::dropIfExists('class_room_student');
}
I'm trying to get the results using laravel many to many relationship but the query is generating wrong therefore it return empty array.
$user->survey()->get() is returning empty array.
$user->survey()->toSql() is returning wrong query:
SELECT
*
FROM
`survey`
INNER JOIN `survey_user` ON `survey`.`id` = `survey_user`.`survey_id`
WHERE
`survey_user`.`user_id` IS NULL
Here, in the end, the user_id should not be null.
Migration for the survey pivot table:
Schema::create('survey_user', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->integer('survey_id')->unsigned();
$table->string('status', 50)->nullable();
$table->timestamps();
});
Schema::table('survey_user', function (Blueprint $table) {
$table->foreign('user_id')->on('users')->references('id');
$table->foreign('survey_id')->references('id')->on('survey')
->onDelete('cascade')
->onUpdate('cascade');
});
}
here are the two relation:
public function survey()
{
return $this->belongsToMany(Survey::class, 'survey_user')
->withPivot('status')
->withTimestamps();
}
public function user()
{
return $this->belongsToMany(User::class, 'survey_user')
->withPivot('status')
->withTimestamps();
}
I'm just trying to get all the users who have survey assigned in their pivot.
$user = new User();
var_dump($user->survey()->get());
I'm just trying to get all the users who have survey assigned in their pivot.
To get all Users where the survey relationship exists, your code would look like this:
$users = User::has('survey')->get();
If you need the survey relationship loaded on the models when you use them, then add with() to eager load the relationship:
$users = User::has('survey')
->with('survey')
->get();
Here, in the end, the user_id should not be null.
The reason it was searching with a null user id is because you are searching with a new User instance that hasn't been saved to the database. This is your code with the problem:
$user = new User();
var_dump($user->survey()->get());
Since $user is a new object that hasn't been saved to the database it doesn't have an id. When you call $user->survey() it builds a query to search survey_user where the user id is null.
I have a table column which holds an array of subject ids selected by the user. There is another table for these subjects and their values. I need to return the values corresponding to the ids saved in the subjects column. To make it more clear suppose that a user have chosen 5 subjects out of 34 subjects and the corresponding ids are saved in the subjects column as a string like this: 2,5,11,21,23
Each of these numbers corresponds to the id of a subject in the subjects table.
//This is the subjects table
public function up()
{
Schema::create('subjects', function (Blueprint $table) {
$table->increments('id');
$table->string('subject', 20);
$table->timestamps();
});
}
//and this is the user_info table
public function up()
{
Schema::create('user_info', function (Blueprint $table) {
...
$table->string('subjects');
...
});
}
How can I return an array of subject values to a view?
// Find whichever user
$user = \App\User::find(1);
// Convert the string of subjects from a string to an array
$subjectIds = explode(',', $user->subjects);
// Load all subjects which match the ids within the subjectIds array
$subjects = \App\Subjects::whereIn($subjectIds)->get();
// Do something with the subjects
foreach($subjects as $subject) {
// Output the subject name
var_dump($subject->name);
}
After some searching around I found that maybe the best solution for my problem was to use the Many to Many relationship. So I removed the subjectscolumn from user_info table. Then I created the pivot table subject_user to save the id of user and their subjects ids in this table.
This is the pivot table schema:
Schema::create('subject_user', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->index();
$table->integer('subject_id')->index();
$table->timestamps();
});
Then in the User and Subject models I established the proper many to many relationship as follows:
//User Model
public function subjects()
{
return $this->belongsToMany('App\Subject')->withTimestamps();
}
//Subject Model
public function users()
{
return $this->belongsToMany('App\User');
}
Finally in the controller i used the attach() and sync() methods to populate or update the pivot table.
//In store method
$user->subjects()->attach($subjects);
//In update method
$user->subjects()->sync($subjects);
The difference between attach and syn is described here.