Laravel - select temporary column where temporary column - laravel

$search_str = "full name search";
$user = App\User::selectRaw("CONCAT(`f_name`, `l_name`) AS `fullname`")
->where('fullname', 'LIKE', '%$search_str%')
->get();
Based on the code above, the column fullname actually does not exist in DB Table. fullname column is just a temporary column.
But when I use it on where clause, Laravel return an error:
Column not found: 1054 Unknown column 'fullname' in 'where clause'

You can use the CONCAT function in your where filter.
$search_str = "full name search";
$user = App\User::selectRaw("CONCAT(`f_name`, `l_name`) AS `fullname`")
->whereRaw("CONCAT(`f_name`, `l_name`) LIKE '%?%'", [$search_str])
->get();

Use Having for aliases. See below reference link.
https://laravel.com/docs/5.6/queries#ordering-grouping-limit-and-offset

Related

Select Specific columns from multiple Table with with() and select ()

I have 2 tables test and goals. One goal has many tests. I would like to fetch data like below.
$tests = test::with('goals')
->where('Goal_id', $goal_id)
->select('test.id as id','goals.Goal_id as goal_id','test.mode as mode')
->get();
But I am getting error Illuminate\Database\QueryException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'goals.Goal_id' in 'field list'
The goals relation is being eager loaded in a separate query so you will not have access to goals.Goal_id in your main query builder, instead you can modify your with() clause to pick specific columns from eager loaded relation as with('goals:Goal_id,another_column')
$tests = test::with('goals:Goal_id')
->where('Goal_id', $goal_id)
->select(['test.id as id','test.mode as mode'])
->get();
This should work:
$tests = DB::table('test')
->select(['test.id as id', 'goals.Goal_id as goal_id', 'test.mode as mode'])
->join('goals', 'goals.id', '=', 'test.goal_id')
->where('Goal_id', $goal_id)
->get();

Eloquent SELECT "string" AS content_type causes errors

I'm using eloquent query builder in Laravel to help me create the equivalent of
SELECT name,'fund' AS content_type FROM fundraisers
This is what I tried:
$db = DB::table('fundraisers')->select("name,'fund' AS content_type")->get()->toArray();
But I get the error
Illuminate\Database\QueryException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'name,'fund'' in 'field list' (SQL: select `name,'fund'` as `content_type` from `fundraisers`)
What am I doing wrong and how do I fix this?
List the columns you want on select like this:
$db = DB::table('fundraisers')
->select('name', DB::raw("'fund' as content_type"))
//...
Check Laravel docs for more info.

date method in eloquent querybuilder

i have this raw query and i want to use it in eloquent query builder
but seems i cant use date method in eloquent and gave me this error im new in eloquent. what is the problem:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'date(prizes.created_at), user_id' in 'group statement' (SQL: select user_id,COUNT(user_id), date(created_at) from `prizes` group by `date(prizes`.`created_at), user_id` having `user_id` = 1 order by `date(created_at)` desc)
raw SQL:
SELECT
user_id,COUNT(user_id), DATE(created_at) FROM prizes
GROUP BY DATE(prizes.created_at), user_id
HAVING user_id = 1
ORDER BY DATE(created_at) DESC
limit 2
Eloquent:
$points = \App\Prize::selectRaw('user_id,COUNT(user_id), date(created_at)')
->groupBy("date(prizes.created_at), user_id")
->orderBy("date(created_at)","DESC")
->having("user_id","=",1)
->get();
what is the the cleanest and best form??
By default, Laravel tries to parse all strings as tables. This means it will add the string between `.
To avoid this, you can put the string in a DB:raw() function to let Laravel know not to parse this string and send it as-is to the database.
->orderBy(\DB::raw("date(created_at)"), "DESC")
Or use the raw method for ordering:
->orderByRaw('date(created_at) desc')

Eloquent in Laravel-Datatables, select in select?

I have 3 tables, the 1st has a FK from the 2nd, and the 2nd has a FK from the 3rd:
Table 1: [admin_demandas]
-------------------------
id_demanda| projec_id
-------------------------
Table 2: [admin_projec]
-------------------------
id_projec | sub_id
-------------------------
Table 3: [admin_sub]
-------------------------
id_sub | name
-------------------------
What I need is to get the 'name' from Table 3 but starting with the Model of the table 1.
I was trying something like this:
$data = AdminDemanda::select([
'id_demanda',
'admin_projec.sub_id AS sub_id',
'admin_sub.name AS name',])
->join('admin_projec', 'admin_demandas.projec_id', '=', 'admin_projec.id_projec')
->join('admin_sub', 'admin_projec.sub_id', '=', 'admin_sub.id_sub')
->get();
return Datatables::of($data)->make(true);
I've done my Datatables with only 1 JOIN (2 tables) but not sure how to do those 2 JOIN (3 tables). I got this error:
[Err] 1054 - Unknown column 'admin_projec.sub_id' in 'on clause'
What should I modify in my query?
Should I need to use query builder instead Eloquent, with a DB::raw() query?
Solved with this:
Inner join between three tables in mysql
it was simple... now in case anyone need it, my Datatable query is:
$datos = AdminDemanda::select([
'id_demanda',
'admin_dis.nombre AS nombre_dist',
'admin_sub.nombre AS nombre_subes',
'mes AS mes_demanda',
'admin_sistemas.nombre AS nombre_sistema',
'admin_demandas.demanda_mwh AS mwh'])
->join('admin_projec', 'admin_demandas.proyeccion_demanda_id', '=', 'admin_projec.id_proyeccion_demanda')
->join('admin_sub', 'admin_projec.subestacion_id', '=', 'admin_sub.id_subestacion')
->join('admin_dis', 'admin_projec.dist_id', '=', 'admin_dis.id_dist')
->join('admin_sistemas', 'admin_projec.sistema_id', '=', 'admin_sistemas.id_sistema')
->get();
You should edit your models
By exemple in AdminSub model
public function projec(){
return $this->hasMany(AdminProjec::class , 'sub_id');
}
You should be able to do
\AdminSub::first()->projec();
And continue by editing your AdminProjec model with the same kind of relationship
public function demandas(){
return $this->hasMany(AdminDemandas::class , 'projec_id');
}
And now you could try
//I do not remember which one will works
\AdminSub::first()->projec()->first()->demandas()->name
//or
\AdminSub::first()->projec()->first()->demandas()->get()->name

Problems with join ERROR: 1054

I tried to use a join, with an array given as a condition:
$task = Task::join('oc_groups', function($join) use ($filter) {
foreach($filter['groups']['data'] as $key => $value) {
$join->on('oc_groups.id', $value);
}
});
But I get the error message :
SQLSTATE[42S22]: Column not found: 1054 Unknown column '1' in 'on clause' (SQL: select oc_tasks.title as task_title from oc_tasks inner join oc_groups on oc_groups.id = 1 where oc_tasks.task_date between 2017-07-01 and 2017-07-31)
The 1 is the content of the $value. What I am doing wrong? - The table oc_groups has a field named id.
As you don't have any relation between these two tables so Try with out join. like this
select `oc_tasks`.`title` as `task_title` from `oc_tasks` ,`oc_groups`
where `oc_tasks`.`task_date` between 2017-07-01 and 2017-07-31 and `oc_groups`.`id` = `1`

Resources