Using Laravel 4.2 & MySQL.
I have an applications table with an id and a fit_score_id column, and a fit_scores table with an id column. It's a basic "belongs to" relationship.
The following code:
$query = Application::join('fit_scores', 'applications.fit_score_id', '=', 'fit_scores.id');
$collection = $query->get();
...produces a collection of Application models with the id property set to the value of the fit_score_id. What am I doing to cause this?
I should note that it is necessary to do this join rather than simply using eloquent relations, because I'm going to want to order the results by a column on the fit_scores table. I don't believe this is possible using Eloquent without an explicit join.
The best way to solve this is by chaining the join method to a select method as following:
Application::select('*', \DB::raw("applications.id as appid"))
->join('fit_scores', 'applications.fit_score_id', '=', 'fit_scores.id')
->get();
Explained: The solution simply suggest that instead of thinking to prevent the behavior of overwriting the first id with the joined id, we can hook into the primary selection query (before joining) and change the label of the id column into something else (in this case 'appid'). By doing so, we end up with both the id of the parent table being labeled 'appid' and the id of the joined table being labeled 'id' again while they lives together on the final result.
I was able to find a possible solution using this answer:
Laravel 4 - JOIN - Same column name
Basically, since Laravel does not automatically prefix column names with table_name. for joined tables, we need to manually work around it by aliasing any conflicting column names in joins. Adding this select statement to my query did it:
->select(DB::raw("applications.*, fit_scores.*, applications.id as id"))
It depends on what you need but probably you can achieve it using eager loading. In case you need to mix joins and eager loading check this out. http://www.jmilan.net/posts/eager-loading-joins-in-laravel
Related
I'm trying to use distinct with pagination but my pagination seems to ignore the total records of my distinct and it makes my pagination all messed up.
I have the following query:
$log_data_list = DB::table('logs')->leftjoin('users','logs.user_id', 'users.id')
->select(DB::raw("distinct on (logs.action,logs.action_table)logs.user_id,users.username as username,logs.created_at as tanggal,logs.ip_client as ip_client,logs.action as tindakan,logs.action_table as tabel,logs.no_laka as no_laka,logs.change_id as id"))
->paginate(5);
Can anyone help me with a solution? Thanks in advance
Instead of using a distinct in this fashion, why not have the log actions stored uniquely in a relational table using methods firstOrCreate / firstOrNew on storing the actual log.
You then would be able to use a proper eloquent model to paginate log actions table that would already be a unique list and use the ID of selection action to get all related logs.
table.logs id,action_id,users_id,...
table.logs_actions id,action_name
This would be less costly than a select distinct especially on a huge table.
I am trying to replace a column in the result of the select query as denoted in
This reference but unlike the example I have many columns in the table thus I can not specify the name of every column in the select query.
I tried some ways to attain the same but none seems effective.
select
*, (REPLACE(REPLACE(role_id,1,"admin"),2,"moderator") AS role_id
from user;
or
Select *
from user
where role_id = (select REPLACE(role_id,1,"admin") as role_id from user;
Here we assume only two possible values for the role_id however at certain instanced it might have to get data from another table ie a different table that holds different ids and values corresponding to them.
So is there a way to attain the following conditions in a single query:-
to replace values of some fields returned from select query (assuming many columns writing the names of all the columns individually is not feasible)
to get the replacement values from different tables for different columns in single table.
I need to implement the above conditions in one query but the changes shouldn't be in the database only the result of select query needs to be optimized.
Already referred to the following too but could not help.
Link 1
Link 2
Link 3
I am using phpmyadmin as engine and php as the implementation language.
If i have understood your question correctly, it's easier to use CASE/WHEN
SELECT *,
CASE WHEN role_id = 1 THEN "admin" WHEN role_id = 2 THEN "moderator" END AS role_id
FROM user;
But easier still maybe to have an array in PHP,
$roles = array("1" => "admin", "2" => "moderator", .... );
and look it up in the array. that will keep your query short and sweet. The advantage of this approach is that you don't need to change your query every time you add a new role. If you get a large number of roles (say dozens) you might actually want a separate table for that.
I have three tables.
Radar data table (with id as primary), also has two columns of violation_file_id, and violation_speed_id.
Violation_speed table (with id as primary)
violation_file table (with id as primary)
I want to select all radar data, limited by 1000, from some start interval to an end interval, joins with violation_speed table. Each radar data must have a violation_speed_id.
I want to then join with the violation_file table, but not each radar records corresponding to violation_file_id, some records just has violation_file_id of 0, means there's no curresponding file.
My current sql is like this,
$results = DB::table('radar_data')
->join('violation_speed', 'radar_data.violation_speed_id', '=', 'violation_speed.id')
->leftjoin('violation_video_file', 'radar_data.violation_video_file_id', '=', 'violation_video_file.id')
->select('radar_data.id as radar_id',
'radar_data.violation_video_file_id',
'radar_data.violation_speed_id',
'radar_data.speed',
'radar_data.unit',
'radar_data.violate',
'radar_data.created_at',
'violation_speed.violation_speed',
'violation_speed.unit as violation_unit',
'violation_video_file.video_saved',
'violation_video_file.video_deleted',
'violation_video_file.video_uploaded',
'violation_video_file.path',
'violation_video_file.video_name')
->where('radar_data.violate', '=', '1')
->orderBy('radar_data.id', 'desc')
->offset($from_id)
->take($max_length)
->get();
It is PHP Laravel. But I think the translation to mysql statement is straight away.
My question is, is it a good way to select data like this? I tried but it seems a bit slow if the radar data grows to a large value.
Thanks.
Assuming you have the proper indices set this is largely the way to go, the only thing that's not 100% clear to me is what the offset() method does, but if it simply adds a WHERE clause than this should give you pretty much the best performance you're going to get. If not, replace it with a where('radar_data.id', '>', $from_id)
The most important indices are the ones on the foreign keys and primary keys here. And make sure not to forget the violate index.
The speed of the query often relies on the use of proper indexing on the joining clause and where clause used.
In your query there are 2 joins and if the joining keys are not indexed then you might need to apply the following
alter table radar_data add index violation_speed_id_idx(violation_speed_id);
alter table radar_data add index violation_video_file_id_idx(violation_video_file_id);
alter table radar_data add index violate_idx(violate);
The ids are primary key hence they are already indexed and should be covered
I wrote a lot of code in codeigniter but I had to restructure my database column prefixes and when I use join queries to join some of my tables in my model's queries there is some tables in one query that have the same id column , I used Alias 'As alias1' for a table name, and model runs successfully without problem
but when I pass the $q = $this->db->get() variable to my controller and then pass it to my view and iterate it like this :
foreach($q->result() as $res)
echo $res->alias1.id;
php errors that unknown $alias1.id but I declared alias1 for one of my tables.
whats the problem ?
Thanks
When you do ->result(), CI will build an array of objects.
Each column declared in your select will be an object member. However, the aliases are not preserved.
It means that SELECT alias.field will be converted as $obj->field not $obj->alias.field.
If you have two fields which have the same name, set an alias inside your SELECT clause
$this->db->select("alias1.field as myfield, alisas2.field as myotherfield");
Then you will be able to get them with $obj->myfield and $obj->myotherfield
I have to call the $model->groupBy(?allcols?) function with all columns as a param.
How should I do this?
Edit: I have all Columns as an Array, so i can't pass them like 'col1','col2',...
I'm asking this because i have this poblem (github) and i found out, that there the prob is on Line 119.
I tried it manually like col1,col2 which worked, but it should by dynamically for all models.
I found this snippet, to get all cols from the current table as an array, but i can only pass a String.
Ok, if I'm understanding your edit correctly, you've got an array of column names you wish to group by. If $model is the name of your query, I'd recommend just using a foreach loop and appending each field:
foreach($allcols as $col){
$model->groupBy($col);
}
$model->get();
There is no such function for grouping all columns but you may use groupBy(col1, col2, ...), for example, if you have a posts table then you may use:
DB::table('posts')->groupBy('col1', 'col2')->get();
Or using Eloquent Model, for example a Post model:
Post::groupBy('col1', 'col2')->get();
If all you're trying to do is get rid of duplicate records (which is all that groupBy(all) would do as far as I can envision), you could also just use $model->distinct() instead. However, unless you add a select() to exclude the id field, you're going to wind up with the full recordset with no grouping, as by definition the id is unique to each record and thus won't collapse across records by either manner.