How to exclude certains columns while using eloquent | Laravel - php

i have an group table. My main table. So i have group_hotels table this table is a pivot table. (id, group_id, hotel_id)
Now in my blade group edit page, i want to list before added pivot table like this code:
My Group model:
public function hotels(){
return $this ->belongsToMany('App\Models\Hotel','group_hotels');
}
My controller:
$group = Group::find($id);
$hotels=Hotel::all();
My blade hotel select2 field:
#foreach($hotels as $hotel)
<option value="{{$hotel->id}}">{{$hotel->name}}</option>
#foreach ($group->hotels as $item)
<option value="{{$item->id}}">{{$item->name}}</option>
#endforeach
#endforeach
The output like this: http://prntscr.com/10v13ed
Now what i want to do, in my group_hotels pivot table, if hotel id exist in group_hotels except the in the pivot table id nothing come hotel table.
In short: If the hotel_id part in the group_hotels table is present in my hotel table, I do not want to call it in the hotel variable.

One option you have is to exclude the Hotel's you don't want in your list at the query level:
Hotel::whereNotKey($group->hotels->modelKeys())->get();

Related

Return employee count based on relationship

I have a employees table and a attendances table
In employees Model
public function Attendance(){
return $this->hasMany(Attendance::class, 'employees_id', 'id');
}
Attendances table i have these column
id, employees_id, in_time, out_time, attendance_status_id, remarks
I want return those employee who has al least one attendance for a specific month which i will input in month field and it will filter based on in_time column
You can use the has() function when getting the Employee details. The has will only return those records if the Employee has any relational data in the Attendance table. You can also refer this link.
$employees = Employee::has('Attendance')->get();
Now you can simply use the count() function the display the total Attendance of the Employee. For the count please refer this link.
#foreach ($employees as $employee)
Total attendance: {{ $employee->Attendance->count() }}
#endforeach

Laravel Eloquent thee tables relationship query

I have three mysql tables :
students (constrained with USER_ID)
student_in_tournament (constrained with STUDENT_ID and TOURNAMENT_ID)
tournaments
I need an eloquent query who take ALL students by specified USER_ID and if these students are in the student_in_tournament table, it needs to join with the tournament table.
If these students are not in the student_in_tournament, they don't need to join something.
At the end, I need ALL students from one specific USER_ID, with the tournament joined if he exists in the student_in_tournament table...
I tried a inner join, but it don't give me ALL the students, only these who are in the student_in_tournament table. I also tried Student::with('studentInTournament.tournaments') but it gives me 'null' in the tournaments
Thanks
Try creating a M:N relation between your Student and Tournament models. Since your table and column names do not conform to what Eloquent expects, you'll need to pass all 4 parameters when creating the relationship.
https://laravel.com/docs/8.x/eloquent-relationships#many-to-many-model-structure
// Student model
public function tournaments()
{
return $this->belongsToMany(Tournament::class, 'student_in_tournament', 'STUDENT_ID', 'TOURNAMENT_ID');
}
https://laravel.com/docs/8.x/eloquent-relationships#many-to-many-defining-the-inverse-of-the-relationship
// Tournament model
public function students()
{
return $this->belongsToMany(Student::class, 'student_in_tournament', 'TOURNAMENT_ID', 'STUDENT_ID');
}
$students = Student::query()
->where('USER_ID', $user_id) // or whereIn('USER_ID', $user_ids) if you have multiple user ids
->with('tournaments')
->get();
https://laravel.com/docs/8.x/blade#loops
#foreach($students as $student)
<!-- show student information -->
#forelse($student->tournaments as $tournament)
<!-- show tournament information -->
#empty
<!-- student has no tournaments -->
#endforelse
<hr>
#endforeach

How to order by column in nested 2 level relationship in Laravel?

I have 3 tables: reports, fields and report_fields which is a pivot between the other 2. What i need to do is order report_field.field by the position column in the field table.
I tried ordering in the relation in the Models or when using with but I may be doing it wrong.
ex:
$query = Report::with([ 'reportFields.field' => function ($q) {
$q->orderBy('position', 'asc');
//$q->orderByRaw("fields.position DESC");
},
Can someone give a basic example of ordering a 2 level nested relationship?
Edit: I do not need to order by any column in the base table but the list of entries in the pivot table by an column in the second table.
Edit2:
To give an example how the output should be ordered:
Report
ReportField
Field.position = 1
ReportField
Field.position = 2
ReportField
Field.position = 3
You can add your needed ordering on the relation of the first table reports:
public function reportFields()
{
return $this->hasMany(ReportFields::class)
->select('report_fields.*')
->join('fields', 'report_fields.field_id', 'fields.id')
->orderBy('fields.position', 'asc');
}

How to find all id pivot from pivot table? (laravel 5.3)

I have a pivot table. The name is users_banks table. The table have field id, user_id, bank_id, status, account_name and account_number
Now, the pivot have 3 records
I display contain from pivot table using code like this :
$user_id = auth()->user()->id;
$user = $this->user_repository->find($user_id);
$account = array();
foreach($user->banks as $bank) {
$account[] = $bank;
}
dd($account);
The result display all record in the form of array. There exist value of field user_id, bank_id, status etc. But I don't find value of id
How can I find id from pivot table?
If the relationship is defined correctly you can use:
$bank->pivot->id
but make sure the user belongsToMany(Bank::class) and the bank belongsToMany(User::class) or else it wont work.

laravel fill selectbox with foreign key

There are 3 tables
Sizes
id
name
Products
id
name
Product_sizes
id
product_id
size_id
I want to fill an selectbox with the id of product_sizes and the name of the foreign key connected table size.
for exampe:
product_sizes.id 1
sizes.name medium
where medium would be found by size_id in product sizes.
How can I the name value in the list?
What i currently have
I can get the right row with
$sizes = $product->sizeAvailable()->lists('pr', 'size_id');
where sizeAvailable is a relation that returns all product_sizes for a selected product.
First of all you don't need an id field in the pivot table because you can uniquely identify each row with the composite key product_id, size_id. A Product can belong to many Sizes and a Size can belong to many Products, thus you shouldn't have duplicate rows.
The relationships of each model are like the following:
class Product extends Model {
public function sizeAvailable() {
return $this->belongToMany('Size', 'product_sizes');
}
}
class Size extends Model {
public function products() {
return $this->belongToMany('Product', 'product_sizes');
}
}
Finally in your View you can use Blade functions to generate your selectbox:
<select>
#foreach($product->sizeAvailable() as $size)
<option value="{{ $size->id }}">{{ $size->name }}</option>
#endforeach
</select>

Categories