Laravel Eloquent ORM filtering with relationship - php

I'm making a filter and there is a problem that I can't solve. The filter uses relationship and it's perfect. But when I make a filter of attribute that doesn't exist in the table it doesn't work. Because the question was too complicated I will give you an example code:
<?php
class School extends Eloquent {
protected $table = 'schools';
public function city(){
return $this->belongsTo('City');
}
public function municipality(){
return $this->belongsTo('Municipality');
}
public function listSchoolsEndUser()
{
$schools_data = new School;
if ( Input::has('district') ) {
$schools_data = $schools_data->whereHas('city', function($q){
$q->where('district_id', '=', Input::get('district'));
});
}
if ( Input::has('municipality') ) {
$schools_data = $schools_data->whereHas('city', function($q){
$q->where('municipality_id', '=', Input::get('municipality'));
});
}
if ( Input::has('city') ) {
$schools_data = $schools_data->where('city_id', '=', Input::get('city'));
}
$schools_data = $schools_data->paginate(12);
return $schools_data;
}
}
And the error is:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'district_id' in 'where clause' (SQL: select count(*) as aggregate from `schools` where (`specialties` like %"5"%) and (select count(*) from `cities` where `schools`.`city_id` = `cities`.`id` and `district_id` = 5) >= 1)
And the example table structure is:
Schools table:
|---------------|
|id|name|city_id|
|---------------|
Cities table:
|-----------------------|
|id|name|municipality_id|
|-----------------------|
Municipalities table:
|-------------------|
|id|name|district_id|
|-------------------|
Districts table:
|-------|
|id|name|
|-------|

Because district_id is two relations away you need to use the dot syntax to target nested relations:
if ( Input::has('district') ) {
$schools_data = $schools_data->whereHas('city.municipality', function($q){
$q->where('district_id', '=', Input::get('district'));
});
}
(This assumes you have a municipality() relation in your Citymodel)

Related

Eloquent relationship

As the title suggests, I have a little problem with the relationship between my tables.
Unknown column 'table1.entity_id' in 'where clause'
select * from `table2` where `table1`.`entity_id` = `table2`.`id`
Here is the structure of my tables:
table1
id varchar(36)
type enum()
entity_id varchar(36)
table2
id varchar(36)
description
table3
id varchar(36)
brand
In the table1.entity_id column we can find the id of table2 and table3.
And these are the relationships:
Table 1
public function table2()
{
return $this->hasMany('App/Model/Table2', 'entity_id');
}
public function table3()
{
return $this->hasMany('App/Model/Table3', 'entity_id');
}
Table 2
public function table1()
{
return $this->belongsTo('App/Model/Table1', 'id', 'entity_id');
}
Table 3
public function table1()
{
return $this->belongsTo('App/Model/Table1', 'id', 'entity_id');
}
And when I do that :
$query->orWhereHas('table2', function($query) use ($value) {
$query->whereNotNull('description');
});
I have this error :
Unknown column 'table1.entity_id' in 'where clause'
select * from `table2` where `table1`.`entity_id` = `table2`.`id`
Can someone tell me what is the problem ?

how to join 4 tables in php laravel?

I Want to extract data from 4 tables .
like sname,cgpa,Group_Cgpa,Room_No and Hostel Name.
Relation of table is as follows.
AllotmentApps has : id,sname,cgpa and grpID (from Group id Table) columns.
Groups has : id,Group_CGPA
Room has : id, HostelID (From Hostel) and ResidentID (From Group id).
Hostels has: id, Name, Total_Rooms.
I'm facing problem in joining the tables. Join with AllotmentApps and Groups works fine, but problem occurs when I joined the Room and Hostel Table.
Join of AllotmentApps and Groups
public function FinalList()
{
$allot_apps = AllotmentApps::join('Groups','Groups.id','AllotmentApps.grpID')->orderBy('Groups.Group_CGPA', 'Desc')->get()->groupBy(
function($item) {
return $item->grpID;
}
) ->take(3);
Join of 4 Tables
public function FinalList()
{
$allot_apps = AllotmentApps::select('sname','cgpa','Group_CGPA','Hostel_Name')->join('Groups','Groups.id','AllotmentApps.grpID')->join('Hostels','Hostels.id','Hostels.HostelID')->join('Rooms','Rooms.id','Hostel.HostelID')->orderBy('Groups.id', 'Asc')->get()->groupBy(
function($item) {
return $item->grpID;
}
) ->take(3);
Try This
$allot_apps=AllotmentApps::select('AllotmentApps .sname','AllotmentApps .cgpa','Groups.Group_CGPA','tablename.Hostel_Name')
->join('Groups','Groups.id','=','AllotmentApps.grpID')
->join('Rooms','Rooms.ResidentID','=','Groups.id')
->join('Hostels','Hostels.id','=','Rooms.HostelID')
->orderBy('Groups.id', 'Asc')
->groupBy()
->get();
public function FinalList()
{ $capasity = Rooms::selectRaw('count(id) as c')->count();
$allot_apps = Rooms::select('Hostel_Name','Rooms.id','Groups.Group_CGPA','AllotmentApps.sname','AllotmentApps.cgpa')->join('Hostels','Hostels.id','Rooms.HostelID')->join('Groups','Groups.id','Rooms.ResidentID')->join('AllotmentApps','Groups.id','AllotmentApps.grpID')->orderBy('Groups.Group_CGPA', 'Desc')->get()->groupBy(
function($item) {
return $item->grpID;
}
) ->take($capasity);
// return $allot_apps;
return view('x', compact('allot_apps'));
}

laravel querying many to many

I have 2 models, Service and Category. They are related with a many-to-many relationship like so:
Service.php
public function categories()
{
return $this->belongsToMany('App\Category')->withTimestamps();
}
Category.php
public function services()
{
return $this->belongsToMany('App\Service')->withTimestamps();
}
And of course they're joined by a pivot table:
category_service
- category_id
- service_id
- created_at
- updated_at
I'd like to use local scope to filter service result based on IDs of categories. I've done the following:
Service.php
public function scopeFilter($query, $category_ids)
{
$services = Service::whereHas('categories', function (Builder $query) use ($category_ids) {
$query->whereIn('category_id', $category_ids)->get();
});
return $services;
}
But I'm getting a Column not found error, specifically:
Column not found: 1054 Unknown column 'services.id' in 'where clause' (SQL: select * from `categories` inner join `category_service` on `categories`.`id` = `category_service`.`category_id` where `services`.`id` = `category_service`.`service_id` and `category_id` in (1, 2))
1 and 2 are the category IDs I pass.
I wrote the function based on the answer I found here and here.
Any pointers?
Your error message show that your query is begin with categories and without join services.
So put the ->get() outside the closure.
public function scopeFilter($query, $category_ids)
{
$services = Service::whereHas('categories', function (Builder $query) use ($category_ids) {
$query->whereIn('category_id', $category_ids);
})->get();
return $services;
}

Search pivot table Eloquent

I have 3 tables
students
- id
- name
classes
- id
- name
student_class
- id
- student_id
- class_id
- score
I want to return a list of the students that belong to class_id = 100
$students = \Student::where(['class_id' => 100])->get();
this is my Student Class
use Illuminate\Database\Eloquent\Model;
class Student extends Model
{
protected $table = 'students';
public function store(Request $request)
{
$student = new Student;
$student->save();
}
}
the error I´m getting is:
<strong>Message:</strong> SQLSTATE[42S22]: Column not found: 1054 Unknown column 'class_id' in 'where clause' (SQL: select * from `students` where (`class_id` = 100))
update: I can do
$students = \Class::find(100)->with(['students'])->get();
and it will return all the students as a child of classes but I don´t need that.
I need the data from students and the pivot table (student_class) in particular de score column.
thank you for your help
Update your student model as
public function classes(){
return $this->belongsToMany(Class::class, 'student_class', 'student_id', 'class_id');
}
//query
Student::whereHas('classes', function ($query) {
$query->where('id', 100);
})->get();
UPDATE : in both of your model relation add
return $this->belongsToMany('App\Class')->withPivot('score');
now you can do this inside your loop
foreach ($student->classes as $class) {
echo $class->pivot->score;
}

Laravel Eloquent - Query builder cant find column with having function

I have a pivot table 'game_genre'(with game_id and genre_id). The game and genre model has a belongsToMany relationship similar to example below.
I have been attempting to gather the games which contain both genre_id of 60 and 55 together. I have been getting the correct result using the following SQL query, but when using the following query builder I end up getting a column not found error when using the having() function.
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'genre_id' in 'having clause'
Im not sure how else to structure the query builder?
MODEL:
class Game extends Model
{
public function genres()
{
return $this->belongsToMany('App\Genre');
}
}
SQL:
SELECT *
FROM game_genre
WHERE genre_id = 55 OR genre_id = 60
GROUP BY game_id
HAVING COUNT(DISTINCT genre_id) = 2;
CONTROLLER:
$game = Game::whereHas('genres', function ($query)
{
$query->where('genre_id', '55')
->orWhere('genre_id', '60')
->groupBy('game_id')
->having('genre_id','=', 2);
})->get();
You forgot the aggregate function (in this case COUNT) in your HAVING condition:
$query->where('genre_id', '55')
->orWhere('genre_id', '60')
->groupBy('game_id')
->havingRaw('COUNT(DISTINCT genre_id) = 2');
Instead of adding several where() and orWhere() to your query, you could also use whereIn() which takes an array:
$myArray = [55,60];
$query->whereIn('genre_id', $myArray)
->groupBy('game_id')
->havingRaw('COUNT(DISTINCT genre_id) = 2');
You can use the following query to get the Games which contain both genre_id of 60 and 55:
$games = Game::whereHas('genres', function ($query) {
$query->where('genre_id', '55');
})
->whereHas('genres', function ($query) {
$query->where('genre_id', '60');
})
->get();

Categories