Codeigniter Aliase not working in Views - php

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

Related

How to use query builder to retrieve array values from different tables?

Following is the code snippet that I have used in my controller:
public function index(Request $request)
{
$query = DB::table('project_files')->select('project_id')->get()->toArray();
dd($query);
return view ( 'filesync/listfiles' )->with ( $query);
}
So when I try passing the values into the view, I get an array which consists of the project_id from the project_files table. What I would want to do now is to retrieve the project_names of these project_ids, stored in the projects table.I need to use the project_id for the same , but am unable to understand how to relate these using query builder.Any help would be appreciated, meaning how do I use the array values in the query retrieving project names from projects table.
You can setup relationships which is the ideal way or you can use a leftJoin with your query:
DB::table('project_files')->select('project_files.project_id')->leftJoin('projects', 'project_files.project_id', '=', 'projects.project_id')->get()->toArray();
and replace the column name respectively to the correct values.
Another suggestion I would make is to actually make use of the M in MVC by defining models for your table instead of using the db facade.
Note: Don't forget to include the columns you wish to select within your select function.

How it works a mysql query with alias?

I'm new in this comunnity and I need to work with a query that get data from a mysql database, I have this query, but I need to add a new table and I don't understand why the query has a alias, I don't know how it works, someone can help me?
This is my query:
SELECT ins.matricula, pe.nombres, pe.appaterno, pe.apmaterno, co.calleynum, co.colonia, co.municipio, co.telfijo, co.telcelular, pe.fechanac, pe.sexo, co.email, pe.institucion, tu.tnombres, tu.tappaterno, tu.tapmaterno, tu.direccion, tu.telefono, ins.fechains, ins.niveledu, ins.fechaini, ins.horario
FROM Inscripciones ins
LEFT JOIN Perfiles pe
ON pe.idperfil=ins.idperfil
LEFT JOIN Contactos co
ON co.idperfil = pe.idperfil
LEFT JOIN Tutores tu
ON tu.matricula = ins.matricula
WHERE pe.idperfil='$var'
I have read the mysql docs but I can't understand how it works.
In MySQL, an "alias" can be declared to simplify the query later.
Typically this is denoted with the "AS" operator, but can also be declared without "AS" - as in your example.
In your example:
SELECT ins.matricula, {...}
FROM Inscripciones ins {...}
The ins is set as an alias for the "Inscripciones" table.
This allows you to use ins throughout the query rather than typing out "Inscripciones." This can be seen in the SELECT statement.
Something to keep in mind - aliases in SQL can be declared after they're first used. This is the case in your example, where SELECT gets ins.matricula before you've actually declared ins as the alias for Inscripciones.
Sometimes this seems counter intuitive, but I promise it will make sense if you experiment with it a bit.
I find it less ambiguous to include the "AS" - which might help it make more sense as you're reading/writing the SQL query.
ex: ... FROM Inscripciones AS ins
To be clear, the use of the alias doesn't change the outcome of your query, but helps you write cleaner queries because you don't have to re-write the tablename every time you want to use it.
A SQL Alias is just what the name says, an alias. It's simply another name (a shorter name) for your table name.
So in your example the table name is Inscripciones, and in this line FROM Inscripciones ins you're saying "ins" is an alias to Inscripciones. Its just a way to make the query smaller/simpler. An alias is like a nickname (i.e. an alias for Michael is "Mike")
Aliases are normally set with "AS" like this:
SELECT * FROM Users AS u
but can be shortened like this:
SELECT * FROM Users u
Tables don't have to have aliases, unless you want to use the same table more than once, but it can make things shorter to type if the tables have columns named the same.
Instead of having to write
SELECT myfulltable1name.id, myfulltable2name.id
You can write
SELECT t1.id, t2.id
(If you've aliased your tables as t1 and t2)
Here's an example query where we use the same table more than once and need an alias to separate them:
SELECT
workAddresses.City as WorkCity,
homeAddresses.City as HomeCity
FROM
Addresses workAddresses
INNER JOIN
Addresses homeAddresses
ON
workAddresses.UserID = homeAddresses.UserID
WHERE
workAddresses.type = 'work' AND
homeAddresses.type = 'home'
Here the Addresses table stores work and home addresses for our users, with a type column to differentiate them. We want a result where tThe work and home address is on the same row, so we have to join the addresses table in twice, we give them sensible aliases so we can tell which is which, and we use where clause to make sure our workAddress table alias only refers to those records with type 'work'
You'll notice I also put an alias on the column names selected, so you can know which is the work City and which is the home city
Sometimes you MUST use an alias, like if you make a subquery, then the result must be aliased in order to be usable:
SELECT
workAddresses.City as WorkCity,
homeAddresses.City as HomeCity
FROM
(SELECT * FROM Addresses WHERE type ='work') workAddresses
INNER JOIN
(SELECT * FROM Addresses WHERE type ='home') homeAddresses
ON
workAddresses.UserID = homeAddresses.UserID
Here we got information from the addresses tables by subquery, and the bracketed sql statements must have aliases
Aliases are always declared at the first point that the object being aliased is brought into the query. For tables, this is in the FROM section, for columns this is in the SELECT section
It might help you to consider it as if the database actually does the from section first, connecting all the tables together, then it does the where, to filter the rows, finally it does the select, to pull just the columns you want. C# has a built in query language called LINQ, that presents things in this more logical way, FROM table WHERE something = something SELECT somecolumns - makes it easier to say "things are aliased when they are first introduced, like variable naming". SQL is what it is, has been for years. You get used to it
Alias in MySQL query is like a temporary short name for your table. They are not necessarily to be used but save your time when you need to create a complex queries. They are mainly used in queries when you use try to fetch data more than 1 table in single query using JOINS.
Suppose you have a table name 'employee_records'. Then trying to fetch the fields for table would look employee_records.id and so on. If you use alias for table name say 'e', then selecting fields will become e.id.
Hope that will make your point clear.
For more information in simple words read about SQL aliases over here - https://www.w3schools.com/sql/sql_alias.asp

Id Column Overwritten by Join

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

Laravel 4 Query groupBy: all columns from table

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.

Codeigniter MySQL a Join Query with a column name collision in the results

I have a very common, run of the mill JOIN query where I have found my self in a bit of a pickle.
My CI DB Query looks like:
$this->db->select()
->from('user_event')
->join('game_bridge', 'user_event.gmeID = game_bridge.gmeID')
->where('user_event.memID', $memID);
Now what I failed to realize up until about a minute ago, is that both tables have a "location" column, however both columns contain unique sets of data to the query results I am looking for overall. With that is there a way to give one location column or the other an alias so I can access the results object for that under a different property name?
If so, how can I do that with CI's DB class/helper?
if you want to get location from both tables you have to give an alias to one or both of them
keep user_event location as it just give alias to game_bridge is like game_bridge.location as game_location
$this->db->select('location,game_bridge.location as game_location')
You can set aliases in your query.
$this->db->select('user_event.location as u_loc, game_bridge.location as g_loc');
But in this case you must enumerate all fields you want to select.

Categories