How to make selection query for join tables in laravel? - php

I have users and staffs tables. I want to display staff details after the login. The staff display will list the of staff with the same section with the user who login. For example, if Adam (section/seksyen=A) login, the staff list displayed are the staffs of section A.
How to make query for that in laravel?
table users:
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
$table->string('section');
$table->string('type');
});
}
table staffs:
public function up()
{
Schema::create('staffs', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->string('nama');
$table->string('emel')->unique();
$table->string('seksyen');
$table->string('jawatan');
$table->string('alamat');
$table->string('no kakitangan');
});
I have tried this query but doesn't work.
$data['data'] = DB::table('staffs')
->join('users', 'users.section', '=', 'staffs.seksyen')
->where('seksyen','=','Auth(section)')->get();

The right code to extract user login section name is :
$section = Auth::user()->section;
$data['data'] = DB::table('staffs')->where('section','=', $section)->get();

Related

how to call the column from main table whose id is being passed as foreign_id in pivot_table in laravel 8?

I am facing an issue while taking columns from the main table and pivot table.
So I have two tables name: users and roles and a pivot table called role_user.
here is the migration of users table:
Schema::create('users', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
Here is the migration of role:
Schema::create('roles', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('slug')->nullable();
$table->timestamps();
});
And here is the migration of pivot table:
Schema::create('role_user', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->id();
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('role_id');
$table->foreign('user_id')->references('id')->on('users');
$table->foreign('role_id')->references('id')->on('roles');
$table->timestamps();
});
And here is the data in the role_user table in PHPMyAdmin:
enter image description here
and here are the relationships:
users:
public function roles() {
return $this->belongsToMany(role::class,'role_user','role_id','user_id')->using(RoleUser::class);
}
And roles:
public function users() {
return $this->belongsToMany(User::class,'role_user','user_id','role_id')->using(RoleUser::class);
}
But now the main thing is I have to show them in table form, where I have to show the name of the user associated with the name of a role assigned to it.
like, User, is tom and role is admin.
how to exactly show them via name in tabular form?
any help? how to solve it?
should I call role_user table and call user under foreach or use pivot method to do this?
So at the part where you want to list the roles for a user you can do something like this in the blade.
#foreach($users as $user)
<tr>
<td>{{$user->name}}</td>
<td>
#foreach($user->roles as $role)
{{$role->name}}
#endforeach
</td>
</tr>
#endforeach
If you only need the timestamps you could use
$this->belongsToMany(role::class,'role_user','role_id','user_id')
->using(RoleUser::class)->withTimestamps();
Or create a model to directly interact with the role_user table.

Select statement with group_concat not working when other columns are called in laravel

Hello my laravel code is
$productDetails = DB::table('products')
->select(DB::raw('products.name, GROUP_CONCAT(sizes.name) as sizesName'))
->join('subcategories', 'products.subcategories_id', '=', 'subcategories.id')
->join('size_categories', 'subcategories.categories_id', '=', 'size_categories.categories_id')
->join('sizes',function($join){
$join->on(DB::raw("FIND_IN_SET(sizes.id, size_categories.size_id)"),">",DB::raw("'0'"));
})
->where('products.id', $request->id)
->get();
This doesnt work, when i useproducts.name or any other column name in select statement
but when i use only group_concat inside Db::raw and nothing else, the query works.
So how do i fetch other columns?
Please help.
I am stuck on it for quite a while
The query i want is
select GROUP_CONCAT(sizes.name),`products`.`name`, `products`.`image`, `products`.`id`, `products`.`image_second`, `products`.`description`, `products`.`min_order`, `size_categories`.`size_id` from `products`
inner join `subcategories` on `products`.`subcategories_id` = `subcategories`.`id`
inner join `size_categories` on `subcategories`.`categories_id` = `size_categories`.`categories_id`
join sizes on (FIND_IN_SET(sizes.id,size_categories.size_id)>0) where `products`.`id` = '7'
Please note that the above query is working fine. I just cant make it in laravel to work. Only the group_concat part.
This is the screenshot from my database, when i dont use group_concat
Also the DISTINCT part is doing nothing there, please ignore it.
I was just trying that out
This is the migration of create_products_table
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('units_id');
$table->unsignedBigInteger('selections_id');
$table->unsignedBigInteger('subcategories_id');
$table->string('name');
$table->string('image');
$table->text('description');
$table->string('min_order');
$table->timestamps();
$table->index('units_id');
$table->index('selections_id');
$table->index('subcategories_id');
});
}
migration of create_subcategories_table
public function up()
{
Schema::create('subcategories', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->unsignedBigInteger('categories_id');
$table->timestamps();
$table->index('categories_id');
});
}
data of size_categories table
public function up()
{
Schema::create('size_categories', function (Blueprint $table) {
$table->id();
$table->string('size_id');
$table->unsignedBigInteger('categories_id');
$table->timestamps();
$table->index('categories_id');
});
}
migration of categories table
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
}
migration of sizes table
public function up()
{
Schema::create('sizes', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
}
In sizes table data is in this form
id name
1 2m
2 3m
3 4m
First, you need to specify select columns separately. Like so:
->select(DB::raw('products.name'), DB::raw('GROUP_CONCAT(sizes.name) as sizesName'))
Next, since group concat is an aggregate column, you need to group the sizes, and product name since it's in the select list and it is not related to size.
->groupBy('size_categories.size_id', 'products.id') //edit after your comment. group by prodcuts.id to be able to select columns from products table.
So your final query should look like this:
$productDetails = DB::table('products')
->select(DB::raw('products.name'), DB::raw('GROUP_CONCAT(sizes.name) as sizesName'))
->join('subcategories', 'products.subcategories_id', '=', 'subcategories.id')
->join('size_categories', 'subcategories.categories_id', '=', 'size_categories.categories_id')
->join('sizes',function($join){
$join->on(DB::raw("FIND_IN_SET(sizes.id, size_categories.size_id)"),">",DB::raw("'0'"));
})
->where('products.id', 7)
->groupBy('size_categories.size_id', 'products.id')
->get();

Laravel save data from one form to different database tables

I want to create a student with some courses.
This is the Laravel view
I created two different tables: a students table
public function up()
{
Schema::create('students', function (Blueprint $table) {
$table->id();
$table->timestamps();
$table->string('student_name');
$table->string('first_name');
$table->string('last_name');
$table->string('email');
});
}
and a courses table.
public function up()
{
Schema::create('student_courses', function (Blueprint $table) {
$table->id();
$table->unsignedInteger('student_id');
$table->string('course_name');
$table->timestamps();
});
}
The students table creates the information of the student and saves it in the student table.
I want to save the courses into the courses table, with the student id. They should have a One to Many relationship. How can I save the different courses into the courses table with the id of the specific student?
You can't store course name in student courses table. You need to create separate tables for courses. After that you can use foreign key for store both the data of student and courses into the student_courses table as per below.
public function up()
{
Schema::create('student_courses', function (Blueprint $table) {
$table->id();
$table->integer('student_id')->unsigned()->nullable();
$table->foreign('student_id')->references('id')->on('students')->onDelete('cascade');
$table->integer('course_id')->unsigned()->nullable();
$table->foreign('course_id')->references('id')->on('courses')->onDelete('cascade');
$table->timestamps();
});
}
Hope this will helps you.
First create Relationship:
In User Model Create:
public function courses(){
return $this->hasMany(Course::class);
}
In Course Model Create:
public function students(){
return $this->belongsTo(Studnet::class);
}
Now in your save function:
$course = new Course($request->all());
$user->courses()->save($course);

Use two tables on a two-to-many relationship or use three tables with a pivot table

Basically, I have 2 tables in my database: Games and Teams.
Every Game must have 2 teams, so it's a two-to-many relationship.
Should I use 2 foreign keys in my Games table pointing to the 2 teams in the Teams table and have a one-to-many relationship, or use many-to-many relationship with a third table to link the games and teams table?
Im using Laravel 6.5 for the project, so I guess im using Eloquent to implement it.
Schema::create('games', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('team_a_id');
$table->foreign('team_a_id')->references('id')->on('teams')->onDelete('restrict');
$table->unsignedBigInteger('team_b_id');
$table->foreign('team_b_id')->references('id')->on('teams')->onDelete('restrict');
$table->unsignedInteger('team_a_score');
$table->unsignedInteger('team_b_score');
$table->string('status');
$table->boolean('finished');
});
Schema::create('teams', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('abbreviation');
$table->string('country');
$table->timestamps();
});
This are the two tables I have created by now, is this the correct way to implement it?
Use a Many to Many Relationship. In that case the Game Modal could have multiple Teams and vice-versa.
Hence the migrations would be like:
Schema::create('games', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('status');
$table->boolean('finished');
});
Schema::create('teams', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('abbreviation');
$table->string('country');
$table->timestamps();
});
Schema::create('game_team', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('game_id');
$table->integer('team_id');
$table->unsignedInteger('score');
$table->timestamps();
});

laravel is there a way to make 3 tables, one table belongs to 2 different tables, with one to one relationship

laravel is there a way to make, one to one relationship, one table belongs to two different tables one to one relationship.
i'm trying to model, a laravel based project, that is voting for ministers.
these are my three models.
members migration. ex: members is working as users for authentication
public function up()
{
Schema::create('members', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('username');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
2.ministers migration file
public function up()
{
Schema::create('ministers', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->mediumText('description');
$table->string('image')->default('no-image.jpg');
$table->unsignedInteger('votes')->default('0');
$table->boolean('status')->default('0');
$table->timestamps();
});
}
3.voters migration file
public function up()
{
Schema::create('voters', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('phone');
$table->enum('education', ['primary', 'intermediate', 'high-school', 'university' ] )->nullable(false)->default('primary');
$table->string('country');
$table->unsignedBigInteger('minister_id');
$table->foreign('minister_id')->references('id')->on('ministers');
$table->unsignedBigInteger('member_id');
$table->foreign('member_id')->references('id')->on('members');
$table->timestamps();
});
}
this voters migration belongs to member and minister, and mister associates one voter, user associates to one voter.
so is this correct way to model, a system like this. which i want every registered member, fill out voting form, which selects a drop down field of the minister to be voted for. and save that form creating a new instance of voter. What i want also is two increment by one minister votes field when ever a new instance of voter is created.

Categories