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

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

Related

Laravel eloquent distinct select with possibility to call relation?

I want to select distinct results from one table, the structure is following:
id, user_id, category_id, last_answered_question_id
I have relation for last_answered_question_id called: lastAnsweredQuestion()
My query is:
Answer::select('category_id')->where(['user_id' => $userId])->distinct()->get();
This query works as expected but in this case I can't call relation $answer = lastAnsweredQuestion.
Is there any known way to get distinct items and call relation lastAnsweredQuestion() anyway?

Laravel: How to get the latest record in group of records with where condition?

I have two tables which are named as students and cities. students table has a primary key which is related to the cities table.
Students table:
In the frontend, I would like to have the data of the cities table with these requirements:
The data of the students table must be grouped by city_id
If there are more than one records with the same city_id in the students table, select only the latest record of the group.
Search in the latest records and select only students who are inactive.
Here is the relationship function of the city model:
public function student()
{
return $this->hasOne(Student::class, 'city_id', 'id')->orderByDesc('id');
}
This is my controller function:
$data = City::whereHas('student', function($query){
$query->where('is_active', 0)
})->with('student')->get();
Expected result: Considering the sample data, the query must return nothing.
Current result: It returns the third row as there is an inactive student record in the second row. So in this case where condition doesn't work properly.
I can get expected result with this SQL query:
select *
from students s
where id = (select max(t2.id)
from students s2
where s.city_id = s2.city_id) AND is_active = '0';
How can I fix this logical error?
What about something like this?
public function inactiveStudent()
{
return $this->hasOne(Student::class, 'city_id', 'id')
->where('is_active', 0)
->orderByDesc('id');
}
$data = City::whereHas('inactive_student')
->with('inactive_student')
->get();
I'm not certain if it's inactive_student or inactiveStudent when you do the query.

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).

custom listing records using conditional

i need some help with my query, basically im trying to get all my order_items on the table, but i need to get all items by user_id, but there is a detail, i want to include also records that includes on a column more than 3 times the the same email on different users_id.
Ex:
table:
- id;
- user_id;
- email;
1- Get all records from mine (user_id); 2 - Get all records where on 3 differentes user_id have the same email value;
Here is my query:
$orders = OrderItem::select('email','user_id')->where('user_id',Auth::user()->id)->distinct('email')->get();
This should work:
$orders = OrderItem::select(DB::raw('count(*) as email_count,email,user_id'))
->groupBy('email')
->where('email_count','>',2)
->orWhere('user_id',Auth::user()->id)
->get();

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