Alias name for model in Laravel 4 - laravel

I am working on Laravel 4.1. I have 4 models for four different tables, but in this query I'm trying to get the count for activity, application and query as I'm using alias for the table name, but I can't to give the alias for the model.
Can anyone explain how to give the alias name for the model?
return $this->model->select('
sud.*,
(select count(saf.userid)
from soca_activity_form saf
where sud.id = saf.userid ) activitycount,
(select count(sa.userid)
from soca_applicationform sa
where sud.id = sa.userid ) applicationcount,
(select count(sqf.userid)
from soca_query_form sqf
where sud.id = sqf.userid ) querycount')
->where('admin','!=',1)
->orderBy('id', 'desc')
->paginate(50);
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '.id = saf.userid ) activitycount ,(select count(sa.userid) from soca_appli' at line 1 (SQL: selectsud.*,(select count(saf.userid) from soca_activity_form saf where sud.id = saf.userid ) activitycount ,(select count(sa.userid) from soca_applicationform sa where sud.id = sa.userid ) applicationcount,(select count(sqf.userid) from soca_query_form sqf where sud.id = sqf.userid ) querycountfromsoca_user_detailswhereadmin!= 1 order byid` desc limit 50 offset 0)

Related

sql query into raw query in laravel

I am new in laravel . I have laravel 5.7 version. and I have query
like
$emp_id = $request->user_id;
$User_workDone_record = DB::select(
DB::raw("
SELECT
(
SELECT access(id) FROM users where id = $emp_id
) as accessid,
a.date as date,
a.day as day,
a.projectname as projectname,
a.clientname as clientname,
task,
start,
(
SELECT users(id) FROM `users` where id = $emp_id
) as user,
end,
TIMEDIFF(end,start) as diff,
workdetails,
id,
rowpages
FROM
workdone as a
where
a.user = '$emp_id'
order by
a.date desc
")
);
but I got issue like :
SQLSTATE[42000]: Syntax error or access violation: 1305 FUNCTION workdoneerp.access does not exist (SQL: SELECT(SELECT access(id) FROM users where id=9) as accessid, a.date as date,a.day as day,a.projectname as projectname,a.clientname as clientname,task,start,end,TIMEDIFF(end,start) as diff,workdetails,id,rowpages FROM workdone as a where a.user='9' order by a.date desc),
How to resolve ?
The problem is access(id) at the start of your SQL query.
The error is telling you the access() function does not exist in your database (workdoneerp).
To solve it you can
create the access() function
or don't use the access() function.

How to join multiple table in Laravel?

I have 3 table
1- planes = name, description
2- presidents = id , p_name
3- plane_president = plane_id , president_id
how to join planes with presidents and plane_president?
$planes = Plane::join('plane_president', 'planes.id', '=', 'plane_president.plane_id')
->join('presidents', 'presidents.id', '=', 'plane_president.president_id');
error:
SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'id' in order clause is ambiguous (SQL: select * from `planes` inner join `plane_president` on `planes`.`id` = `plane_president`.`plane_id` inner join `presidents` on `presidents`.`id` = `plane_president`.`president_id` order by `id` asc limit 10 offset 0)
plane_president is a pivot table for president and planes, you can declare the relationship at the Plane.php model:
public function presidents()
{
return $this->belongsToMany(
President::class,
'plane_president',
'plane_id',
'president_id');
}
and use it like:
plane->presidents;
when you want to retrieve the presidents for a particular plane in a controller.
You have 2 columns named id as the error says it is ambiguous.
order by id asc limit 10 offset 0 here you aren't specifying by which column to order planes.id or presidents.id

How to convert raw sql to laravel fluent query builder

hello every one please i need help how would I go about this select using Laravel's query builder? I am aware I can use a raw sql query but I would like to avoid that. Any help would be appreciated, thanks in advance!
SELECT SUM(COST) FROM (
SELECT COUNT(STOCK_ID)*PRICE COST
FROM STOCK ST INNER JOIN PRODUCT PDT ON PDT.PROD_ID=ST.PROD_ID
WHERE PROD_NAME='PENCIL' LIMIT 6 GROUP BY STOCK_ID) TB
The reason why i avoid the raw sql is because when i try it like this
private function totalprice( $product_id)
{
$selltotal =
DB::raw("SELECT SUM(sell_rate)
FROM
(SELECT COUNT(stock_id) * stock_rate
FROM tbl_stock AS st
INNER JOIN tbl_product AS pdt ON pdt.product_id = st.produck_id
WHERE produck_name = 'product_id'
LIMIT 6)
GROUP BY stock_id");
return $selltotal;
}
This is the error i get
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT SUM(sell_rate)
FROM
(SELECT COUNT(stock_id) * stock_rate ' at line 1 (SQL: insert into `tbl_sell` (`category_id`, `brand_id`, `product_id`, `buyer_id`, `sell_quantity`, `sell_total_price`, `sell_date`, `added_by`, `entry_time`) values (3, 5, 6, 3, 2, SELECT SUM(sell_rate)
FROM
(SELECT COUNT(stock_id) * stock_rate
FROM tbl_stock AS st
INNER JOIN tbl_product AS pdt ON pdt.product_id = st.produck_id
WHERE produck_name = 'product_id'
LIMIT 6)
GROUP BY stock_id, 2017-08-11, 0, 2017-08-11 07:34:11))
please i will be very greatfull if i get a solution to my problem. Thanks in advance
hello i succeded in doing it myself. It may help some one someday
private function totalprice( $product_id)
{
$selltotal = DB::table('tbl_stock')
->select(array(DB::raw('count(stock_id)*stock_rate')))
->where('tbl_stock.product_id', $product_id)
->join('tbl_product','tbl_stock.product_id','=', 'tbl_product.product_id')
->groupby('stock_id')
->sum('stock_rate');
return $selltotal;
}

how to pass select subquery in where clause using laravel

This is my SQl query
select sum(stock.total_in_stock) as total_in_stock
,stock.name
,stock.inventory_id
from (
select i.store_id
,i.model_id
,i. total_in_stock
,i.id as inventory_id
, m.*
from `inventory` as `i`
left join `model_store` as `ms` on `ms`.`store_id` = `i`.`store_id`
left join `model` as `m` on `m`.`id` = `ms`.`model_id`
where `i`.`model_id` = m.id
and `m`.`status` = 1
and `ms`.`status` = 1
and `i`.`created_at` = (
select si.created_at
from inventory AS si
where si.model_id = i.model_id
and si.store_id = i.store_id
and si.status=1
order by si.created_at desc limit 1
)
) as stock
group by stock.model_id
In laravel, it is written as this:
$results1 = DB::table('inventory as i')
->select(DB::raw( 'sum(stock.total_in_stock) as total_in_stock,stock.name,stock.inventory_id FROM ( SELECT i.store_id,i.model_id,i. total_in_stock,i.id as inventory_id, m.* '))
->leftJoin('model_store as ms','ms.store_id','=','i.store_id')
->leftJoin('model as m','m.id','=','ms.model_id')
->where('i.model_id','=', 'm.id')
->where('m.status','=', '1')
->where('ms.status','=', '1')
->where("i.created_at","=",function($query) {
$query->select(DB::raw("si.created_at FROM inventory AS si WHERE si.model_id = i.model_id AND si.store_id = i.store_id AND si.status=1 ORDER BY si.created_at DESC LIMIT 1)) as stock GROUP BY stock.model_id"));
});
It gives me the following error:-
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 1 (SQL: select sum(stock.total_in_stock) as total_in_stock,stock.name,stock.inventory_id FROM ( SELECT i.store_id,i.model_id,i. total_in_stock,i.id as inventory_id, m.* from `inventory` as `i` left join `model_store` as `ms` on `ms`.`store_id` = `i`.`store_id` left join `model` as `m` on `m`.`id` = `ms`.`model_id` where `i`.`model_id` = m.id and `m`.`status` = 1 and `ms`.`status` = 1 and `i`.`created_at` = (select si.created_at FROM inventory AS si WHERE si.model_id = i.model_id AND si.store_id = i.store_id AND si.status=1 ORDER BY si.created_at DESC LIMIT 1 )) as stock GROUP BY stock.model_id))
It takes 2 closing brackets at the end and gives the above error. Please help me writing the above SQL query in laravel.
Answering your question that's in the tile: the subquery where needs fix:
->where("i.created_at", function($query) {
$query->from('inventory as si')
->selectRaw('max(si.created_at)')
->whereRaw('si.model_id = i.model_id AND ...');
});
However, in order to create a subquery in the from clause, you need to pass raw query, so your whole code requires a bit of toSql() and setBindings(...), which is cumbersome.
So to get the answer to your problem, better describe the problem itself instead.

Using a helper function to change a field of a query in Laravel 4 using DB:raw

I have a query function that I am using to pull some data from my database. I also have a function that changes around the "created_at" field to print it like so: Month Day YY'
Here is the query function:
public static function friend_activity_json($start = 0, $number_of_posts = 2) {
$friend_activity = DB::table('fanartists')
->join('fans', 'fanartists.fan_id', '=', 'fans.id')
->join('artists', 'fanartists.artist_id', '=', 'artists.id')
->orderBy('fanartists.created_at', 'DESC')
->select(DB::raw('StringEdit::getDate(fanartists.created_at) as created_at, fans.fbid, fans.first_name, fans.last_name, fans.gender, fans.city, fanartists.artist_id, artists.stage_name'))
->get();
The function is in the folder helpers, in a filed called "StringEdit.php". The function is getDate:
public static function getDate($date) {
$full_date = explode(" ", $date);
$date_pieces = explode("-", $full_date[0]);
$year = substr($date_pieces[0], -2);
$monthNum = $date_pieces[1];
$monthName = date("F", mktime(0, 0, 0, $monthNum, 10));
$final_date = $monthName ." ". $date_pieces[2] ." '".$year;
return $final_date;
}
I have been able to call this function elsewhere, so I know it works. How do I get it to work in this context to change around my "created_at" field? When running this I get the error:
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '::getDate(fanartists.created_at) as created_at, fans.fbid, fans.first_name, fans' at line 1 (SQL: select StringEdit::getDate(fanartists.created_at) as created_at, fans.fbid, fans.first_name, fans.last_name, fans.gender, fans.city, fanartists.artist_id, artists.stage_name from `fanartists` inner join `fans` on `fanartists`.`fan_id` = `fans`.`id` inner join `artists` on `fanartists`.`artist_id` = `artists`.`id` order by `fanartists`.`created_at` DESC) (Bindings: array ( ))
EDIT: New Error:
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '"%M %d %y) as created_at, fans.fbid, fans.first_name, fans.last_name, fans.gende' at line 1 (SQL: select DATE_FORMAT(fanartists.created_at, "%M %d %y) as created_at, fans.fbid, fans.first_name, fans.last_name, fans.gender, fans.city, fanartists.artist_id, artists.stage_name from `fanartists` inner join `fans` on `fanartists`.`fan_id` = `fans`.`id` inner join `artists` on `fanartists`.`artist_id` = `artists`.`id` order by `fanartists`.`created_at` DESC) (Bindings: array ( ))
This won't work like the way you used it in your query here
DB::raw('StringEdit::getDate(fanartists.created_at) as created_at, fans.fbid, fans.first_name, fans.last_name, fans.gender, fans.city, fanartists.artist_id, artists.stage_name')
Here, getDate function is being treated as mysql function and it's not valid, anyways, you can use mysql's native DATE_FORMAT function instead, like
DATE_FORMAT(fanartists.created_at, "%M %d %y") as created_at
Check the documentation.

Resources