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

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

Related

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

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

using raw query in where methods makes error in query generation

I have an eloquent query as
Role::where("(company_id = Auth::user()->company_id or name = 'admin')and id in(2,3)")->pluck('name');
According to my eloquent the sql should be as
select `name` from `roles` where ( company_id = 1 or name = admin ) and id IN (2, 3) and `roles`.`deleted_at` is null
But it executes as
select `name` from `roles` where ( company_id = 1 or name = admin ) and id IN (2, 3) is null and `roles`.`deleted_at` is null
Can anyone help me concluding why extra is null condition is applied in the query?
Note: I am using soft deletes
You should use whereRaw instead of where
Role::whereRaw("(company_id = Auth::user()->company_id or name = 'admin')and id in(2,3)")->pluck('name');

how to get latest record from the database having same id in laravel?

I am trying to to get latest record having the same id. For example
I have table
ID | Created_at
1 |2016-04-26
1 |2016-04-20
1 |2016-04-18
2 |2016-04-27
2 |2016-04-19
I want to get result like this
ID | Created_at
1 |2016-04-26
2 |2016-04-27
How do I do this in Laravel? I was only able to order the record by descending order. Don't know how to pick the latest record of each ID. Thank you.
Try using Collections service from laravel , and use last() method. Example:
$data = ModelName::all();
$last_data_object = collect($data)->last();
//try to see the object using var_dump()
var_dump($last_data_object);
I get it from https://laravel.com/docs/5.2/collections#method-last
You can try with whereRaw to getting last records in groupBy laravel
$data = Table::whereRaw('Created_at IN (select MAX(Created_at) FROM table GROUP BY ID)')->get();
Try it this way, it will give you the max grouped ID which will be the latest:
SELECT MAX(ID), Created_at
FROM table
GROUP BY ID, Created_at
Thank you everyone for help. I was able to solve this by
DB::raw("SELECT ID,created_at FROM <table name> a WHERE created_at=(SELECT max(created_at) FROM <table name> b WHERE a.ID=b.ID)
DB::raw('SELECT * FROM `test` WHERE 1 GROUP BY `ID` ORDER BY `Created_at` ASC');
Try this
Include the directive Db
$id = DB::table('your_table')->orderBy('id', 'desc')->value('id');
If you have user_id.
$id = DB::table('your_table')->where('user_id', $user_id)->orderBy('id', 'desc')->value('id');

Laravel query builder updating field based on select count from another table

I have a Post and for each post there are multiple Likes in the likes table. I have created a total_likes field in the Posts table and I want to update it with the total number of likes from the likes table, in one statement. I current have this:
DB::table('posts as p')
->update(['total_likes' => function($query) {
$query->select(DB::raw('COUNT(*)'))
->from('likes as l')
->where(DB::raw('p.id = l.post_id'))
->groupBy('l.post_id');
}]);
But I am getting an error:
Object of class Closure could not be converted to string
I'm essentially trying to run:
UPDATE posts SET total_likes = (SELECT COUNT(id) FROM likes WHERE likes.post_id = posts.id GROUP BY 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