Is there a way to make this query faster - mysql

I have this query and it runs in like 0.5s I need it to be faster is there a way to make this happen
$events_id = Event::where('user_id', Auth::user()->id)
->select("id")
->orderByDesc('id')->pluck('id');
$total_visitors_count = Visitor::select(DB::raw('count(*) as num_visits'))
->join('event_visitor', 'visitors.id', '=', 'event_visitor.visitor_id')
->whereIn('event_visitor.event_id', $events_id)
->count();

Relationships in laravel are a good way to keep our queries simple and fast, you can make relations between your entities to handle this:
User model class:
public function events()
{
return $this->hasMany(Event::class);
}
Event model class:
public function user()
{
return $this->belongsTo(User::class);
}
public function visitors()
{
return $this->belongsToMany(Visitor::class, 'event_visitor');
}
Visitor model class:
public function events()
{
return $this->belongsToMany(Event::class, 'event_visitor');
}
now, your queries become like this:
$events_id = auth()->user()->events()->orderByDesc('id')->pluck('id');
$total_visitors_count = Visitor::with('events')
->whereHas('events', fn ($q) => $q->whereIn('id', $events_id))
->count();

Related

Group by and Sum of One-To-Many relation tables in Eloquent

I have a requirement.
My DB has tables like the following.
The tables have OneToMany (1-n) parent-child relation.
Table School (id, school_name)
Table Class (id, school_id, class_name)
Table Section (id, class_id, section_name, no_of_seats)
Table Student (id, section_id, student_name, ....)
When Some Student is registered, data is uploaded to the Student table.
Now, I want to have a statistic like
| school_name | total_seats | student_registered |
and for a particular school
| class_name | total_seats | student_registered |
How to achieve this in Laravel/Eloquent
Thanks in Advance
Probably it works with:
Counting/Summarizing HasMany relations
Counting/Summarizing HasManyThrough relations
Counting/Summarizing HasManyDeep relations
Definition
class Section extends Model
{
public function students(): HasMany
{
return $this->hasMany(Student::class);
}
public function scopeWithRegisteredStudents(Builder $query): Builder
{
// Count HasMany relation
return $query->withCount('students as students_registered');
}
}
// The word "Class" is reserved, so we need to use "SchoolClass" instead
class SchoolClass extends Model
{
protected $table = 'classes';
public function sections(): HasMany
{
return $this->hasMany(Section::class, 'class_id');
}
public function students(): HasManyThrough
{
return $this->hasManyThrough(Student::class, Section::class, 'class_id');
}
public function scopeWithTotalSeats(Builder $query): Builder
{
// Summarize field from HasMany relation
return $query->withSum('sections as total_seats', 'no_of_seat');
}
public function scopeWithRegisteredStudents(Builder $query): Builder
{
// Count HasManyThrough relation
return $query->withCount('students as students_registered');
}
}
class School extends Model
{
public function classes(): HasMany
{
return $this->hasMany(SchoolClass::class);
}
public function sections(): HasMany
{
return $this->hasManyThrough(Section::class, SchoolClass::class, null, 'class_id');
}
public function students(): HasManyThrough
{
// https://github.com/staudenmeir/eloquent-has-many-deep
return $this->hasManyDeep(Student::class, [SchoolClass::class, Section::class], ['school_id', 'class_id', 'section_id'], ['id', 'id', 'id']);
}
public function scopeWithTotalSeats(Builder $query): Builder
{
// Summarize field from HasManyThrough relation
return $query->withSum('sections as total_seats', 'no_of_seat');
}
public function scopeWithRegisteredStudents(Builder $query): Builder
{
// Count HasManyDeep relation
return $query->withCount('students as students_registered');
}
}
Example
// Fetching simply
Section::query()
->withRegisteredStudents()
->get();
SchoolClass::query()
->withTotalSeats()
->withRegisteredStudents()
->get();
School::query()
->withTotalSeats()
->withRegisteredStudents()
->get();
// Fetching with nested relations
School::query()
->withTotalSeats()
->withRegisteredStudents()
->with(['classes' => function (HasMany $query) {
return $query
->withTotalSeats()
->withRegisteredStudents();
}])
->get();
If you use a static analyzer like PHPStan or Psalm, you can alternatively use scopes method to prevent errors.
School::query()
->scopes(['withTotalSeats', 'withRegisteredStudents'])
->get();
This is not what you asked for as it uses Query Builder instead of Eloquent. I have not tested it as I have nothing to test against currently but this should work -
use Illuminate\Support\Facades\DB;
$students_per_section = DB:table('students')
->select('section_id', DB::raw('COUNT(id) AS num_students'))
->groupBy('section_id')
$query = DB:table('schools')
->join('classes', 'schools'.'id', '=', 'classes.school_id')
->join('sections', 'classes.id', '=', 'sections.class_id')
->leftJoinSub($students_per_section, 'students_per_section', function($join) {
$join->on('sections.id', '=', 'students_per_section.section_id')
});
if ($school_id) {
$query
->select('classes.class_name', DB::raw('SUM(no_of_seats) AS total_seats'), DB::raw('SUM(students_per_section.num_students) AS student_registered'))
->where('schools.id', '=', $school_id)
->groupBy('classes.class_name')
} else {
$query
->select('schools.school_name', DB::raw('SUM(no_of_seats) AS total_seats'), DB::raw('SUM(students_per_section.num_students) AS student_registered'))
->groupBy('schools.school_name')
}
$stats = $query->get();

many-to-many relationship: order by on pivot table not working

I have these relationship between school and associate models:
// School model
public function associates()
{
return $this->belongsToMany('Associate', 'school_associate', 'school_id', 'associate_id')
->withPivot('start_date', 'end_date');
}
// Associate model
public function schools()
{
return $this->belongsToMany('School', 'school_associate', 'associate_id', 'school_id')
->withPivot('start_date', 'end_date');
}
I need to get all associates of one school ordered by start_date.
This is what I tried without success (in this try I am searching in all schools):
dd(\App\Associate::with(['schools' => function ($q) {
$q->orderBy('pivot_start_date', 'desc');
}])->toSql());
And I get this sql (notice no order by clause):
select * from `associate`
I tried to edit the relationship like this:
// Associate model
public function schools()
{
return $this->belongsToMany('School', 'school_associate', 'associate_id', 'school_id')
->withPivot('start_date', 'end_date')
->orderBy('pivot_start_date', 'desc'); // also tried without "pivot_"
}
And according to this post, I also tried :
// Associate model
public function schools()
{
return $this->belongsToMany('School', 'school_associate', 'associate_id', 'school_id')
->withPivot('start_date', 'end_date')
->orderBy('school_associate.start_date', 'desc');
}
But I always get the same query and the results are not ordered.
I solved using query builder in this way.
This function is in Associate model:
public function scopeLast($query, $school_ids = [])
{
$query->join('school_associate', "{$this->table}.{$this->primaryKey}", '=', 'school_associate.associate_id')
->join('school', 'school.school_id', '=', 'school_associate.school_id')
->whereIn('school.school_id', $school_ids)
->orderBy('school_associate.start_date', 'desc');
return $query;
}

hasOne with null-able in laravel not working

I have a customer table which has a field called 'policy_id', where policy_id points to policy table. It is a null-able field, ie. Some customers may not have a policy.
I have a relationship code like this in Customer.php
public function policy() {
return $this->hasOne('App\Models\Policy', "id", "policy_id");
}
But when I issue a search request I am getting error like this:
Illuminate\Database\Eloquent\ModelNotFoundException: No query results for model [App\Models\Policy]
If I modify the function like this:
public function policy() {
if ($this->getAttribute('policy_id')) {
return $this->hasOne('App\Models\Policy', "id", "policy_id");
} else {
return null
}
}
But I am getting an error like this:
Call to a member function getRelationExistenceQuery() on null
Here is my search code:
$c = new Customer();
return Customer::doesntHave('policy')->orWhere(function (Builder $query) use ($req) {
$query->orWhereHas('policy', function (Builder $query) use ($req) {
$p = new Policy();
$query->where($req->only($p->getFillable()))
->orWhereBetween("policy_period_from", [$req->policy_period_start_from, $req->policy_period_start_to])
->orWhereBetween("policy_period_to", [$req->policy_period_end_from, $req->policy_period_end_to])
->orWhereBetween("payment_date", [$req->payment_date_from, $req->payment_date_to]);
});
})->where($req->only($c->getFillable()))->get();
Am I missing something or are there any other ways to do this?
PS: While debugging the above search code is returning successfully, but the exception happening from somewhere inside Laravel after the prepareResponse call.
Thanks in advance.
return $this->hasOne('App\ModelName', 'foreign_key', 'local_key');
Change the order, put the foreign_key policy_id in front of id
In your Customer Model, you need to use belongsTo method:
public function policy() {
return $this->belongsTo('App\Models\Policy', "policy_id", "id");
}
And In your Policy Model, use hasOne:
public function customer() {
return $this->hasOne('App\Models\Customer', "policy_id", "id");
}
First of all, you placed the wrong params.
$this->belongsTo('App\Models\Policy', "FK", "PK");
public function policy() {
return $this->belongsTo('App\Models\Policy','policy_id', 'id');
}
And for null value of policy_id you can use withDefault();
public function policy() {
return $this->belongsTo('App\Models\Policy','policy_id', 'id')->withDefault([
'name' => 'test'
]);;
}
there's a number of problems there but can you perhaps specify the namespace and the class of both your models - Customer and Policy.
By default, the models you create with php artisan make:model will use the \App namespace e.g. \App\Customer and \App\Policy.
Just double check that.
Also, with regards to the relationship, if the Laravel conventions have been followed you could just:
In the Customer model
public function policy() {
return $this->belongsTo(Policy::class);
}
In the Policy model
public function customer() {
return $this->hasOne(Customer::class);
}
of if a multiple customers can be under one policy
public function customers() {
return $this->hasMany(Customer::class);
}
Good luck

Method chainning for join table with pagination on CI 3

I create a core class named MY_Model that extends CI_Model. In this class, I create a method chaining to get all record with pagination like this :
// Take record with paging.
public function get_all_paged()
{
// get argument that passed
$args = func_get_args();
// get_all_paged($offset)
if (count($args) < 2) {
$this->get_real_offset($args[0]);
$this->db->limit($this->_per_page, $this->_offset);
}
// get_all_paged(array('status' => '1'), $offset)
else {
$this->get_real_offset($args[1]);
$this->db->where($args[0])->limit($this->_per_page, $this->_offset);
}
// return all record
return $this->db->get($this->_tabel)->result();
}
So , I just used like this on my controller,
for example
public function index($offset = NULL) {
$karyawan = $this->karyawan->get_all_paged($offset); //get all
}
I am realy confuse to get all record using join, I know join in CI like this :
public function get_all_karyawan() {
$this->db->select('tb_1 , tb_2');
$this->db->from('tb_1');
$this->db->join('tb_2', "where");
$query = $this->db->get();
return $query->result();
}
How to make it into chain in MY_Model?
Any help it so appreciated ...
The good thing in query builder, you can chain your db methods, till get(). So you can define, selects, where queries, limits in different ways.
For example:
public function category($category)
{
$this->db->where('category_id', $category);
return $this;
}
public function get_posts()
{
return $this->db->get('posts')->result();
}
And you can get all posts:
$this->model->get_posts();
Or by category:
$this->model->category(2)->get_posts();
So upon this, in your model:
public function get_all_karyawan() {
$this->db->select('tb_1 , tb_2');
$this->db->join('tb_1', "where");
// Here you make able to chain the method with this
return $this;
}
In your controller:
public function index($offset = NULL) {
$karyawan = $this->karyawan->get_all_karyawan()->get_all_paged($offset);
}

Querying 'across' pivot table

I have two models, beers and distributions, which have a many-to-many relationship. The pivot model hasMany kegs, which contain some relevant information to the beer such as pricing and status. When I build my beer index, I need all the information of the beer model, the distributor model, and the keg model. What I am trying to figure out is how to query for all the information in an efficient manner. Here is my current query:
Keg's are scoped on status:
public function scopeStatus($query, $status)
{
return $query->where('status', '=', $status);
}
and I build my beers index with:
$kegs = Keg::status($status)->get();
$beers=[];
foreach ($kegs as $keg){
$beer = Beer::find($keg->beer_distribution->beer_id);
$distributor = Distributor::find($keg->beer_distribution->distributor_id);
$beers[]=[
'beer' => $beer,
'keg' => $keg,
'distributor' => $distributor];
}
return $beers;
I know that this is a slow query but im not sure how to do this in a single query. Is there a way that I can run this faster?
Some relevant model code:
class Beer extends Eloquent {
public function distributors()
{
return $this->belongsToMany('Distributor', 'beer_distributions');
}
class BeerDistribution extends Eloquent {
protected $fillable = ['beer_id', 'distributor_id'];
public function kegs()
{
return $this->hasMany('Keg', 'beer_distribution_id');
}
class Distributor extends Eloquent {
public function beers()
{
return $this->belongsToMany('Beer', 'beer_distributions');
}
class Keg extends Eloquent {
public function scopeStatus($query, $status)
{
return $query->where('status', '=', $status);
}
public function beerDistribution()
{
return $this->belongsTo('BeerDistribution');
}
}
So I figured out that what I really needed to do was add my query building relations on my Keg model (which was the fatherest 'down' in the nest of relations), and then use eager loading!
I now build my beers index like so:
$beers=[];
foreach (Keg::status($status)
->with('kegsize',
'beerDistribution.beer.brewery',
'beerDistribution.beer.style',
'beerDistribution.distributor')->get() as $keg){
$beers[]=$keg;
}
return $beers;
This brings me down to a stunning total of 10 queries.