SQLSTATE[42S22]: (SQL: select * from `categories` where `categories`.`departement_id` = 1 and `categories`.`departement_id` is not null) - laravel-5

I'm trying to select all categories of a specific departement.
class Test extends Controller
{
public function test(){
$depts=Departement::find(1)->categories;
foreach ($depts as $dept){
echo $dept->name;
}
return view('test');
}
}

A quick google search tells me SQLSTATE[42S22] is the code for 'Column not found'.
When you call Departement::find(1)->categories, Eloquent makes 2 queries
Get THE Department whe primary key is equal to 1
Get ALL the Categories where their 'departement_id' attribute is equal to 1
Given the query in your error
select * from `categories` where `categories`.`departement_id` = 1 and `categories`.`departement_id` is not null)
It's clear there is no departement_id column in your categories table.
If there's no departement_id column in your categories table
Either:
Add it in a migration.
Add it directly in the db if you do not work with migrations
If you want to make another column act as the foreign key
update your relationship method to reflect that.
https://laravel.com/docs/5.8/eloquent-relationships

Related

Laravel query builder select all except specific column

I have 2 tables with the same columns except the second table have one more column, this column is foreign key of the first;
what i want is to make union query;but for union the column must the same; so i want to select all column except for the column distinct;
The easy way is to provide in select all the same column:
$a = Table1::select(['column1', 'column2', 'etc...']);
$b = Table2::select(['column1', 'column2', 'etc...']);
and go with $a->union($b)->get();
but if i have too much column, i end up with so much column to provide in the select function; so what i want is to provide in the query the column that i don't want to retrieve;
i can put protected $hidden in the second table model but for some reason i need this distinct column on some other query;
Get all columns name by Schema::getColumnListing($table);
And computes the intersection of arrays
array_intersect($columnsName1, $columnsName2);
I haven't done it with 2 tables but I am using collections and rejecting certain columns on a similar project:-
$row = Table1::firstOrFail();
$exclude=['column_1', 'column_2'];
return collect(array_keys($row->getAttributes()))
->reject(function ($name) use ($row, $exclude) {
return in_array($name, $row->getHidden())
|| in_array($name, $exclude);
}
);

Laravel ambiguous key in 'where' clause

I have a customer class and a pet class which has a many to many relationship. There is a pivot table customer_pet. Both the customers table and the pets table have a team_id.
When I write the following code:
$results = auth()->user()->team->customers();
$results->leftJoin('customer_pet', 'customer_pet.customer_id', '=', 'customers.id');
$results->leftJoin('pets', 'pets.id', '=', 'customer_pet.pet_id');
return $results->get()->load('pets');
I get this error:
SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'team_id' in where clause is ambiguous (SQL: select * from `customers` left join `customer_pet` on `customer_pet`.`customer_id` = `customers`.`id` left join `pets` on `pets`.`id` = `customer_pet`.`pet_id` where `customers`.`team_id` = 2 and `customers`.`team_id` is not null and `customers`.`deleted_at` is null and `team_id` = 2
I tried making the relation in the Customer model look like this:
public function team()
{
return $this->belongsTo(Team::class, 'customers.team_id', 'teams.id');
}
but I get the same result. I am missing something obvious but I am not sure what?
Any help would be appreciated. Thanks.
select * from `customers` left join `customer_pet` on `customer_pet`.`customer_id` = `customers`.`id` left join `pets` on `pets`.`id` = `customer_pet`.`pet_id` where `customers`.`team_id` = 2 and `customers`.`team_id` is not null and `customers`.`deleted_at` is null and `team_id` = 2
The query in the exception shows that there is a team_id = 2 at the end. It seems that you're adding a $query->where('team_id', 2) without qualification somewhere in your code.
You can use $query->qualifyColumn($column) to prepend the table name automatically.

How to get records from a table if it does not exist in another related table laravel query builder

I have two tables
tb_teachers
-----------
id
name
school_id
tb_class_to_teachers
--------------------
id
teacher_id
class_id
assigned_status
school_id
How to get records from tb_teachers if it(teacher_id and school_id) does not exist in another related table tb_class_to_teachers using laravel query builder
I assume you set up your relationship correctly, then u may use doesntHave
$teachers = App\Teachers::doesntHave('class')->get();
try this
$classToTeachers = DB::table('tb_class_to_teachers')->get();
if($classToTeachers->teacher_id == null && $classToTeachers->school_id == null)
{
$teacher = DB::table('tb_teachers')->get();
}

Laravel Eloquent select function cause empty relation

Following is my query
$user = User::select(['uuid','name','about'])->with(['education','work'])->first();
this returns empty data for relationship education and work,
but if I remove select function from query I am getting data in relationship and it also returns all columns of user table which I don't want.
how can solve this problem
The problem is that relationships (with(...)) execute an additional query to get the related results. Let's say you have one to many relationship where users have many works. User::with('work')->find(1) will then execute these 2 queries:
select user where id = 1 and select works where user_id = 1.
So basically in order to be able to execute the second query (fetch relationship data) you need to include id (or whichever column you're referencing) in you select statement.
Fix:
$user = User::select(['uuid','name','about', 'id'])->with(['education','work'])->first();
Same principle in different forms applies to all relationships. For example in the inverse of hasMany which is belongsTo you would need to select the foreign key (for example user_id).

Laravel 4.2 - Update a pivot by its own id

I'm having some trouble with my pivot table. I've recognized too late, that it is possible, that some pivot rows doesn't have unique values in my project, means I've to add an auto_increment ID field to my pivot table.
This is my structure:
Order.php
public function items()
{
return $this->belongsToMany('Item', 'orders_items', 'order_id', 'item_id')->withPivot(['single_price', 'hours', 'prov', 'nanny_id', 'vat', 'vat_perc', 'invoice_id','id']);
}
orders_items
id, order_id, item_id, nanny_id, hours
I've conntected Orders and Items through a pivot table ('orders_items)'. It is possible, that one order has 2 or more same items in the pivot table. So I've to add an unique ID to identify and update them.
Now I try to update a pivot row. Problem is, if I have 2 or more items, he updates them all, not only one. This is my update command:
$order = Order::find($orderId);
$items = $order->items()->whereNull('nanny_id');
$free_item = $items->first();
$free_item->pivot->nanny_id = 123;
$free_item->pivot->save();
With this command, he updates all pivot rows from the order. I know the problem: Laravel uses here the wrong identifiers (it uses order_id and item_id as defined in my belongsToMany relationship - and they aren't unique). For example, Laravel tries to execute this code on save():
UPDATE orders_items SET [...] WHERE order_id = 123 AND item_id = 2;
I want, that Laravel changes the query to this one:
UPDATE orders_items SET [...] WHERE order_id = 123 AND item_id = 2 AND id = 45;
// Edit
Okay, this solution works:
$free_item->pivot->where('id',$free_item->pivot->id)->update('nanny_id',123);
But is there an easier way, f.e. adding a custom pivot model that adds the id automatically to save() and update() methods?

Resources