Search pivot table Eloquent - php

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;
}

Related

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;
}

How to query a customize key in Laravel?

Considering this tables: person and employee to which connected to person by person_id. This person_id is also the Primary & Foreign key of employee table. Thus in my migrations, i have this:
Schema::create('employees', function (Blueprint $table) {
$table->bigIncrements('person_id');
$table->foreign('person_id')->references('id')->on('persons')->onDelete('cascade');
});
and my show method is like this one
public function show(Employee $employee){
dd($employee->person_id);
$employee = Employee::where('person_id', $employee->person_id)->orderBy('employee_number', 'asc')->join('persons', 'employees.person_id', '=', 'persons.id')->first();
return view('employee.show', compact('employee'));
}
But i am experiencing this issue:
Illuminate\Database\QueryException
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: select * from `employees` where `id` = 5 limit 1)
Does the query is not aware of the column i am using?
Change the primary key in the Employee model
class Employee extends Model
{
/**
* The primary key associated with the table.
*
* #var string
*/
protected $primaryKey = 'person_id';
public function person()
{
return $this->belongsTo('App\Employee', 'person_id', 'person_id');
}
}
Then query using find
Employee::find($employee->person_id)->with('person')->first();
orderBy and first are redundant on one result queries
And if you want to return the Employee with the Person, just access the relationship object (employee is returned from route model binding)
public function show(Employee $employee) {
$person = $employee->person;
return view('employee.show', compact('employee', 'person'));
}
Hope this helps

Laravel 5.3 hasManyThrough through an intermediate table

I have the following table relationship:
organizations
id - integer
organization_users
organization_id - integer (FK)
user_id - integer (FK)
users
id - integer
I am trying to get all the users of an organization through eloquent relationships. Here is my Organization.php model with its relationships:
class Organization extends Model
{
public function Users(){
return $this->hasManyThrough('App\User', 'App\OrganizationUser',
'organization_id', 'user_id', 'id');
...
}
I have tried many combinations of that relationship such as
return $this->hasManyThrough('App\User', 'App\OrganizationUser',
'user_id', 'organization_id', 'id');
But all turn up somewhat the same error (this one is from the first query):
Illuminate\Database\QueryException with message 'SQLSTATE[42S22]: Column not
found: 1054 Unknown column 'organization_users.id' in 'on clause' (SQL: select
`users`.*, `organization_users`.`organization_id` from `users` inner join
`organization_users` on `organization_users`.`id` = `users`.`user_id` where
`organization_users`.`organization_id` = 1)'
Is it possible that I can have the relationship retrieve the user_id to query on the users table instead of Laravel trying to retrieve organization_users.id? If not is there another way around this?
This is many to many relationship.
User Model:
public function organizations()
{
return $this->belongsToMany('App\Organization','organization_users');
}
Organization Model:
public function users()
{
return $this->belongsToMany('App\User','organization_users');
}
To, get all the users with their organizations:
$users=User::with('organizations')->get();
foreach($users as $user)
{
print_r($user->name);
foreach($user->organizations as $organization)
{
print_r($organization->name);
}
}
What you are describing looks like it may be a 'Many-to-Many' relationship.
https://laravel.com/docs/5.3/eloquent-relationships#many-to-many

Laravel Eloquent ORM filtering with relationship

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)

Getting to use Eloquent hasMany() relationship

I have a table of categories in which my categories and their title and thumbnails are stored.
I have another table in which images are stored.
The third table is a joint table. I store in each record of it, the id of the image and the id of the category.
Table Schema:
id
cat_id
item_id
Now I want to get a cat_id by query_string and then pass it to the function for it to get the list of all images with this category in the database.
I'm confused about how to write the method. I have written the following method for CategoryList model which throws error:
class CategoryList extends Eloquent
{
protected $table = "categories_list";
function Images ()
{
return $this->hasMany("Image", 'id');
}
}
And here is the usage in the Image model:
return CategoryList::Images()->where("cat_id", '=', $catid)->get()->toArray();
But it throws the following error:
{"error":{"type":"Illuminate\\Database\\QueryException","message":"SQLSTATE[42S22]: Column not found: 1054 Unknown column 'cat_id' in 'where clause' (SQL: select * from `images` where `images`.`id` is null and `cat_id` = 19)","file":"C:\\wamp\\www\\aone\\vendor\\laravel\\framework\\src\\Illuminate\\Database\\Connection.php","line":539}}
class Category extends Eloquent {
public function images()
{
return $this->belongsToMany('Image');
}
}
Then do:
$images= Categorie::find($catid)->images;
In this case, your pivot table is 'category_image', but if you need to choose another name, it must be specified
return $this->belongsToMany('Image', 'your_pivot_table_name', 'cat_id', 'item_id');
Please visit http://laravel.com/docs/eloquent#many-to-many for more information

Categories