Laravel, Datatables, column with relations count - php

I have two models, User and Training, with Many to many relationship between them. I'm using the Laravel Datatables package to display a table of all the users. This is how the data controller method (which retrieves the query results and creates a Datatables table) looks like:
public function getData()
{
$users = User::select(array('users.id', 'users.full_name', 'users.email', 'users.business_unit', 'users.position_id'))
->where('users.is_active', '=', 1);
return \Datatables::of($users)
->remove_column('id')
->make();
}
How can I add a column to the created table which displays the total number of relations for each user (that is, how many Trainings does each User have)?

The brute force way would be to try a User::selectRaw(...) which has a built in subquery to get the count of trainings for the user and expose it as a field.
However, there is a more built-in way to do this. You can eager load the relationship (to avoid the n+1 queries), and use the DataTables add_column method to add in the count. Assuming your relationship is named trainings:
public function getData() {
$users = User::with('trainings')->select(array('users.id', 'users.full_name', 'users.email', 'users.business_unit', 'users.position_id'))
->where('users.is_active', '=', 1);
return \Datatables::of($users)
->add_column('trainings', function($user) {
return $user->trainings->count();
})
->remove_column('id')
->make();
}
The name of the column in add_column should be the same name as the loaded relationship. If you use a different name for some reason, then you need to make sure to remove the relationship column so it is removed from the data array. For example:
return \Datatables::of($users)
->add_column('trainings_count', function($user) {
return $user->trainings->count();
})
->remove_column('id')
->remove_column('trainings')
->make();
Edit
Unfortunately, if you want to order on the count field, you will need the brute force method. The package does its ordering by calling ->orderBy() on the Builder object passed to the of() method, so the query itself needs the field on which to order.
However, even though you'll need to do some raw SQL, it can be made a little cleaner. You can add a model scope that will add in the count of the relations. For example, add the following method to your User model:
Note: the following function only works for hasOne/hasMany relationships. Please refer to Edit 2 below for an updated function to work on all relationships.
public function scopeSelectRelatedCount($query, $relationName, $fieldName = null)
{
$relation = $this->$relationName(); // ex: $this->trainings()
$related = $relation->getRelated(); // ex: Training
$parentKey = $relation->getQualifiedParentKeyName(); // ex: users.id
$relatedKey = $relation->getForeignKey(); // ex: trainings.user_id
$fieldName = $fieldName ?: $relationName; // ex: trainings
// build the query to get the count of the related records
// ex: select count(*) from trainings where trainings.id = users.id
$subQuery = $related->select(DB::raw('count(*)'))->whereRaw($relatedKey . ' = ' . $parentKey);
// build the select text to add to the query
// ex: (select count(*) from trainings where trainings.id = users.id) as trainings
$select = '(' . $subQuery->toSql() . ') as ' . $fieldName;
// add the select to the query
return $query->addSelect(DB::raw($select));
}
With that scope added to your User model, your getData function becomes:
public function getData() {
$users = User::select(array('users.id', 'users.full_name', 'users.email', 'users.business_unit', 'users.position_id'))
->selectRelatedCount('trainings')
->where('users.is_active', '=', 1);
return \Datatables::of($users)
->remove_column('id')
->make();
}
If you wanted the count field to have a different name, you can pass the name of the field in as the second parameter to the selectRelatedCount scope (e.g. selectRelatedCount('trainings', 'training_count')).
Edit 2
There are a couple issues with the scopeSelectRelatedCount() method described above.
First, the call to $relation->getQualifiedParentKeyName() will only work on hasOne/hasMany relations. This is the only relationship where that method is defined as public. All the other relationships define this method as protected. Therefore, using this scope with a relationship that is not hasOne/hasMany throws an Illuminate\Database\Query\Builder::getQualifiedParentKeyName() exception.
Second, the count SQL generated is not correct for all relationships. Again, it would work fine for hasOne/hasMany, but the manual SQL generated would not work at all for a many to many relationship (belongsToMany).
I did, however, find a solution to both issues. After looking through the relationship code to determine the reason for the exception, I found Laravel already provides a public method to generate the count SQL for a relationship: getRelationCountQuery(). The updated scope method that should work for all relationships is:
public function scopeSelectRelatedCount($query, $relationName, $fieldName = null)
{
$relation = $this->$relationName(); // ex: $this->trainings()
$related = $relation->getRelated(); // ex: Training
$fieldName = $fieldName ?: $relationName; // ex: trainings
// build the query to get the count of the related records
// ex: select count(*) from trainings where trainings.id = users.id
$subQuery = $relation->getRelationCountQuery($related->newQuery(), $query);
// build the select text to add to the query
// ex: (select count(*) from trainings where trainings.id = users.id) as trainings
$select = '(' . $subQuery->toSql() . ') as ' . $fieldName;
// add the select to the query
return $query->addSelect(DB::raw($select));
}
Edit 3
This update allows you to pass a closure to the scope that will modify the count subquery that is added to the select fields.
public function scopeSelectRelatedCount($query, $relationName, $fieldName = null, $callback = null)
{
$relation = $this->$relationName(); // ex: $this->trainings()
$related = $relation->getRelated(); // ex: Training
$fieldName = $fieldName ?: $relationName; // ex: trainings
// start a new query for the count statement
$countQuery = $related->newQuery();
// if a callback closure was given, call it with the count query and relationship
if ($callback instanceof Closure) {
call_user_func($callback, $countQuery, $relation);
}
// build the query to get the count of the related records
// ex: select count(*) from trainings where trainings.id = users.id
$subQuery = $relation->getRelationCountQuery($countQuery, $query);
// build the select text to add to the query
// ex: (select count(*) from trainings where trainings.id = users.id) as trainings
$select = '(' . $subQuery->toSql() . ') as ' . $fieldName;
$queryBindings = $query->getBindings();
$countBindings = $countQuery->getBindings();
// if the new count query has parameter bindings, they need to be spliced
// into the existing query bindings in the correct spot
if (!empty($countBindings)) {
// if the current query has no bindings, just set the current bindings
// to the bindings for the count query
if (empty($queryBindings)) {
$queryBindings = $countBindings;
} else {
// the new count query bindings must be placed directly after any
// existing bindings for the select fields
$fields = implode(',', $query->getQuery()->columns);
$numFieldParams = 0;
// shortcut the regex if no ? at all in fields
if (strpos($fields, '?') !== false) {
// count the number of unquoted parameters (?) in the field list
$paramRegex = '/(?:(["\'])(?:\\\.|[^\1])*\1|\\\.|[^\?])+/';
$numFieldParams = preg_match_all($paramRegex, $fields) - 1;
}
// splice into the current query bindings the bindings needed for the count subquery
array_splice($queryBindings, $numFieldParams, 0, $countBindings);
}
}
// add the select to the query and update the bindings
return $query->addSelect(DB::raw($select))->setBindings($queryBindings);
}
With the updated scope, you can use the closure to modify the count query:
public function getData() {
$users = User::select(array('users.id', 'users.full_name', 'users.email', 'users.business_unit', 'users.position_id'))
->selectRelatedCount('trainings', 'trainings', function($query, $relation) {
return $query
->where($relation->getTable().'.is_creator', false)
->where($relation->getTable().'.is_speaker', false)
->where($relation->getTable().'.was_absent', false);
})
->where('users.is_active', '=', 1);
return \Datatables::of($users)
->remove_column('id')
->make();
}
Note: as of this writing, the bllim/laravel4-datatables-package datatables package has an issue with parameter bindings in subqueries in the select fields. The data will be returned correctly, but the counts will not ("Showing 0 to 0 of 0 entries"). I have detailed the issue here. The two options are to manually update the datatables package with the code provided in that issue, or to not use parameter binding inside the count subquery. Use whereRaw to avoid parameter binding.

I would setup your DB tables and Eloquent models using the conventions provided at http://laravel.com/docs/4.2/eloquent. In your example you would have three tables.
trainings
training_user
users
Your models would look something like this.
class Training {
public function users() {
return $this->belongsToMany('User');
}
}
class User {
public function trainings() {
return $this->belongsToMany('Training');
}
}
You can then use Eloquent to get a list of users and eager load their trainings.
// Get all users and eager load their trainings
$users = User::with('trainings')->get();
If you want to count the number of trainings per user you can simply iterate over $users and count the size of the trainings array.
foreach ( $users as $v ) {
$numberOfTrainings = sizeof($v->trainings);
}
Or you can simply do it in pure SQL. Note that my example below assumes you follow Laravel's conventions for naming tables and columns.
SELECT
u.*, COUNT(p.user_id) AS number_of_trainings
FROM
users u
JOIN
training_user p ON u.id = p.user_id
GROUP BY
u.id
Now that you have a couple of ways to count the number of relations, you can use whatever method you like to store that value somewhere. Just remember that if you store that number as a value in the user table you'll need to update it every time a user creates/updates/deletes a training (and vice versa!).

Related

Exclude join columns from Laravel scope query ONLY_FULL_GROUP_BY error

I have a scope query in a Laravel project which is implicitly fetching two columns which I don't want in the result set, because they are causing an ONLY_FULL_GROUP_BY error, I don't want to disable this database condition.
We have the following relations:
Organisation has -> Categories
public function categories()
{
return $this->belongsToMany(
Category::class,
'organisation_unit_template_categories',
'organisation_unit_id',
'template_category_id'
);
}
Categories has -> Templates
public function templates()
{
return $this->hasMany(Template::class);
}
Template has -> Dimensions
public function dimensions()
{
return $this->belongsTo(Dimensions::class, 'dimensions_id');
}
Our categories also have a scope query, so that we can get all categories which contain at least one template who's dimensions have 'digital = 0'
public function scopeIsPrint($query)
{
return $query
->select($this->getTable().'.*')
->join('templates', 'template_categories.id', '=', 'templates.category_id')
->join('template_dimensions', 'template_dimensions.id', '=', 'templates.dimensions_id')
->where('template_dimensions.digital', 0)
->groupBy($this->getTable().'.id');
}
We call the scope query from a controller like so:
$categories = $this->organisation->categories()->isPrint()->get();
This is outputting:
SELECT
`template_categories`.*,
`organisation_unit_template_categories`.`organisation_unit_id` AS `pivot_organisation_unit_id`,
`organisation_unit_template_categories`.`template_category_id` AS `pivot_template_category_id`
FROM
`template_categories`
INNER JOIN
`organisation_unit_template_categories` ON `template_categories`.`id` = `organisation_unit_template_categories`.`template_category_id`
INNER JOIN
`templates` ON `template_categories`.`id` = `templates`.`category_id`
INNER JOIN
`template_dimensions` ON `template_dimensions`.`id` = `templates`.`dimensions_id`
WHERE
`organisation_unit_template_categories`.`organisation_unit_id` = 2
AND `template_dimensions`.`digital` = 0
AND `template_categories`.`deleted_at` IS NULL
GROUP BY `template_categories`.`id`
How can I make sure that these two columns:
`organisation_unit_template_categories`.`organisation_unit_id` AS `pivot_organisation_unit_id`,
`organisation_unit_template_categories`.`template_category_id` AS `pivot_template_category_id`
are not included in the query, and bonus point for letting my know why they are implicitly added in the first place.
Many Thanks
Our categories also have a scope query, so that we can get all categories which contain at least one template who's dimensions have 'digital = 0'
My suggestion is to rewrite the query to use exists instead of join and group by.
public function scopeIsPrint($query)
{
return $query
->whereExists(function($q) {
return $q->selectRaw('1')->from('templates')
->join('template_dimensions', 'template_dimensions.id', '=', 'templates.dimensions_id')
->whereRaw('template_categories.id=templates.category_id')
->where('template_dimensions.digital', 0)
})
}

data repeating when two tables are joined in codeigniter

I tried to fetch data using joins and the data is repeating,
The controller code is:
public function searchjobs2()
{
//$id=$_SESSION['id'];
$lan = $_POST["picke"]; //var_dump($id);die();
$value['list']=$this->Free_model->get_jobs($lan);//var_dump($value);die();
$this->load->view('free/header');
$this->load->view('free/searchjobs2',$value);
}
And the model:
public function get_jobs($lan)
{
$this->db->select('*');
$this->db->from("tbl_work_stats");
$this->db->join("tbl_work", "tbl_work.login_id = tbl_work_stats.login_id",'inner');
$this->db->where("language LIKE '%$lan%'");
// $this->db->where('tbl_work_stats.login_id',$id);
$this->db->order_by('insertdate','asc');
$query=$this->db->get()->result_array();//var_dump($query);die();
return $query;
}
I have used
foreach ($list as $row){
...
}
for listing.
Using distinct will remove duplicate fields:
$this->db->distinct();
From what I can see, your query has ambiguity, and an error in the join statement, also your where like is part of the problem, I would recommend trying this even do there are some missing info, find out wich field you need to join from the second table.
public function get_jobs($lan){
$this->db->select("tbl_work_stats.*, tbl_work.fields");
$this->db->from("tbl_work_stats");
$this->db->join("tbl_work", "tbl_work_stats.login_id = tbl_work.login_id","inner");
$this->db->where("tbl_work.language LIKE", "%" . $lan . "%" );
$this->db->order_by("tbl_work_stats.insertdate","asc");
$query=$this->db->get()->result_array();
return $query;}
do you mean to join on login_id?
I am guessing that is the user logging in and it is the same for many entries of tbl_work_stats and tbl_work.
you didn't post your schema, , but login_id doesn't seem like right thing to join on. how about something like tbl_work.id = tbl_work_stats.tbl_work_id or similar?
also CI $db returns self, so you can do:
public function get_jobs(string $lan):array
{
return $this->db->select()
->from('tbl_work_stats')
->join('tbl_work','tbl_work.id = tbl_work_stats.work_id')
->like('language',$lan)
->order_by('insertdate')
->get()
->result_array();
}

Eloquent join using "USING" clause with N query

I'm using Slim Framework with Illuminate Database.
I want to make JOIN query with USING clausa. Let's say given Sakila database. Diagram:
How to make join with USING clause (not ON) in eloquent model ?
SELECT film_id,title,first_name,last_name
FROM film_actor
INNER join film USING(film_id) -- notice
INNER join actor USING(actor_id) -- notice
What I want is an eager loading with EXACT 1 query. The use of eloquent relationships described in the API is not meeting my expectation, since any eager relation use N+1 query. I want to make it less IO to database.
FilmActor model :
class FilmActor extends Model
{
protected $table = 'film_actor';
protected $primaryKey = ["actor_id", "film_id"];
protected $increamenting = false;
protected $appends = ['full_name'];
// i need to make it in Eloquent model way, so it easier to manipulate
public function getFullNameAttribute()
{
$fn = "";
$fn .= isset($this->first_name) ? $this->first_name ." ": "";
$fn .= isset($this->last_name) ? $this->last_name ." ": "";
return $fn;
}
public function allJoin()
{
// how to join with "USING" clause ?
return self::select(["film.film_id","title","first_name","last_name"])
->join("film", "film_actor.film_id", '=', 'film.film_id')
->join("actor", "film_actor.actor_id", '=', 'actor.actor_id');
//something like
//return self::select("*")->joinUsing("film",["film_id"]);
//or
//return self::select("*")->join("film",function($join){
// $join->using("film_id");
//});
}
}
So, in the controller I can get the data like
$data = FilmActor::allJoin()
->limit(100)
->get();`
But there's a con, if I need to add extra behavior (like where or order).
$data = FilmActor::allJoin()
->where("film.film_id","1")
->orderBy("film_actor.actor_id")
->limit(100)
->get();`
I need to pass table name to avoid ambiguous field. Not good. So I want for further use, I can do
$kat = $request->getParam("kat","first_name");
// ["film_id", "title", "first_name", "last_name"]
// from combobox html
// adding "film.film_id" to combo is not an option
// passing table name to html ?? big NO
$search = $request->getParam("search","");
$order = $request->getParam("order","");
$data = FilmActor::allJoin()
->where($kat,"like","%$search%")
->orderBy($order)
->limit(100)
->get();`
In Eloquent (and I think that was already available in 2018) the feature is not named using but with and should give something like :
ForumActor::with(['film', 'actor'])->get();
Of course this has to be adapted to your cases, you may even nest relationships :
ForumActor::with('actor.contacts')->get();
For instance.
Have a look : https://laravel.com/docs/8.x/eloquent-relationships#eager-loading
Even though it's labelled as "Eager Loading" (which is great btw) it also works without eager loading, and moreover, when foreign keys are properly set (e.g. with migrations), then it uses only ONE query, so that keeps away the N+1 Problem.
You can try find in code is possible to make USING JOIN, or add some proxy dictionary:
$kat_dict = ["film_id" => "film.film_id", "title"=> 'title', "first_name" => 'first_name', "last_name" => 'last_name'];
$kat = $kat_dict[$request->getParam("kat","first_name")];
BTW: better way is using function like Arr::get($arr, $index, $default) (See at code example)
You can simply call raw query via select
$query = "SELECT
film_id,title,first_name,last_name
FROM
film_actor
INNER join film USING(film_id)
INNER join actor USING(actor_id)
WHERE
film.film_id = :filmId
ORDER BY film_actor.actor_id
LIMIT 0, 100";
$data = DB::select($query, [
'filmId' => 1
]);
// or like this, if not using default connection
/**
$data = DB::connection('test')->select($query, [
'filmId' => 1
]);
*/

Laravel eloquent limit results

I have a working query:
Object::all()->with(['reviews' => function ($query) {
$query->where('approved', 1);
}])
And I want to limit the number of reviews, per object, that is returned. If I use:
Object::all()->with(['reviews' => function ($query) {
$query->where('approved', 1)->take(1);
}])
or
Object::all()->with(['reviews' => function ($query) {
$query->where('approved', 1)->limit(1);
}])
it limits the total number of reviews, where I want to limit the reviews that are returned by each object. How can I achieve this?
Eloquent way
Make one relationship like below in your model class
public function reviews() {
return $this->hasMany( 'Reviews' );
}
//you can pass parameters to make limit dynamic
public function firstReviews() {
return $this->reviews()->limit( 3 );
}
Then call
Object::with('firstReviews')->get();
Faster way(if you just need one review)
Make a derived table to get the latest review 1st and then join it.
Object->select('*')
->leftJoin(DB::raw('(SELECT object_id, reviews FROM reviews WHERE approved=1 ORDER BY id DESC limit 0,1
as TMP'), function ($join) {
$join->on ( 'TMP.object_id', '=', 'object.id' );
})
->get();
Grabbing 1 child per parent
You can create a helper relation to handle this very easily...
In your Object model
public function approvedReview()
{
return $this->hasOne(Review::class)->where('approved', 1);
}
Then you just use that instead of your other relation.
Object::with('approvedReview')->get();
Grabbing n children per parent
If you need more than 1, things start to become quite a bit more complex. I'm adapting the code found at https://softonsofa.com/tweaking-eloquent-relations-how-to-get-n-related-models-per-parent/ for this question and using it in a trait as opposed to a BaseModel.
I created a new folder app/Traits and added a new file to this folder NPerGroup.php
namespace App\Traits;
use DB;
trait NPerGroup
{
public function scopeNPerGroup($query, $group, $n = 10)
{
// queried table
$table = ($this->getTable());
// initialize MySQL variables inline
$query->from( DB::raw("(SELECT #rank:=0, #group:=0) as vars, {$table}") );
// if no columns already selected, let's select *
if ( ! $query->getQuery()->columns)
{
$query->select("{$table}.*");
}
// make sure column aliases are unique
$groupAlias = 'group_'.md5(time());
$rankAlias = 'rank_'.md5(time());
// apply mysql variables
$query->addSelect(DB::raw(
"#rank := IF(#group = {$group}, #rank+1, 1) as {$rankAlias}, #group := {$group} as {$groupAlias}"
));
// make sure first order clause is the group order
$query->getQuery()->orders = (array) $query->getQuery()->orders;
array_unshift($query->getQuery()->orders, ['column' => $group, 'direction' => 'asc']);
// prepare subquery
$subQuery = $query->toSql();
// prepare new main base Query\Builder
$newBase = $this->newQuery()
->from(DB::raw("({$subQuery}) as {$table}"))
->mergeBindings($query->getQuery())
->where($rankAlias, '<=', $n)
->getQuery();
// replace underlying builder to get rid of previous clauses
$query->setQuery($newBase);
}
}
In your Object model, import the trait use App\Traits\NPerGroup; and don't forget to add use NPerGroup right under your class declaration.
Now you'd want to setup a relationship function to use the trait.
public function latestReviews()
{
return $this->hasMany(Review::class)->latest()->nPerGroup('object_id', 3);
}
Now you can use it just like any other relationship and it will load up the 3 latest reviews for each object.
Object::with('latestReviews')->get();

Performing a sum() on a collection in Laravel

I have an application with a basic forum system where users can "like" a topic multiple times. My models extend Eloquent and I'm trying to get the sum of votes a user has for a specific topic... Basically, I'm trying to accomplish something like:
$votes = Auth::user()
->votes->has('topic_id', '=', $topic->id)
->sum('votes');
However, when executing this, I get the following error...
Call to a member function sum() on a non-object
I've also tried
public function show($forumSlug, $topicSlug)
{
$topic = Topic::whereSlug($topicSlug)->first();
$votes = Topic::whereHas('votes', function ($q) use ($topic)
{
$q->where('topic_id', '=', $topic->id)->sum('votes');
});
dd($votes);
}
However, with that I receive an error stating:
Unknown column 'ideas.id' in 'where clause' (SQL: select sum(votes)
as aggregate from votes where votes.idea_id = ideas.id and
idea_id = 1)`
You may try something like this (Not sure about your relationship but give it a try):
$topic = User::with(array('topics' => function ($query) use ($topic_id) {
// $query = Topic, so it's: Topic::with('votes')
$query->with('votes')->where('topics.id', $topic_id);
}))->find(Auth::user()->id)->topics->first();
// Count of total votes
dd($topic->votes->count());
P/S: If it doesn't work then please post your model's relationship methods.
I managed to get it working, though I'm not sure I like this approach. I'd love to hear if anyone knows of a better way of doing this...
Basically, I used my relationships to filter() the votes and then used sum() on the filtered collection.
public function show($forumSlug, $topicSlug)
{
$userId = is_null(Auth::user()) ? false : Auth::user()->id;
$topic = Topic::whereSlug($topicSlug)->first();
$votes = $topic->votes->filter(function ($votes) use ($userId)
{
return $votes->user_id == $userId;
})->sum('votes');
return View::make('forums.topics.show', compact('topic', 'votes'));
}

Categories