Actually i have an table with some columns, but i need to filter some columns, those 3 i`ll need:
id | tipodemonstrativo | anoreferencia
---+-------------------+--------------
01 | AN | 2015
02 | AN | 2016
03 | SE | 2014
04 | PB | 2015
I did this with raw SQL
SELECT anoreferencia,
CASE tipodemonstrativo
WHEN 'PB' THEN CONCAT(anoreferencia, '-03-31')
WHEN 'SE' THEN CONCAT(anoreferencia, '-06-30')
WHEN 'SB' THEN CONCAT(anoreferencia, '-09-30')
WHEN 'AN' THEN CONCAT(anoreferencia, '-12-31')
END AS referencia
FROM demonstrativofinanceiro
ORDER BY referencia DESC
LIMIT 4
It results something link this:
id | referencia
---+------------
01 | 2015-12-31
02 | 2016-12-31
03 | 2014-06-30
04 | 2015-03-31
I`m trying to reach same result with DQL approach, but with no success. I did this in raw SQL but gives an array:
$em = $this->getDoctrine()->getManager();
$query = "SELECT *,
CASE tipodemonstrativo
WHEN 'PB' THEN CONCAT(anoreferencia, '-03-31')
WHEN 'SE' THEN CONCAT(anoreferencia, '-06-30')
WHEN 'SB' THEN CONCAT(anoreferencia, '-09-30')
WHEN 'AN' THEN CONCAT(anoreferencia, '-12-31')
END AS referencia
FROM demonstrativofinanceiro
ORDER BY referencia DESC
LIMIT 4";
$stmt = $em->getConnection()->prepare($query);
$stmt->execute();
$result = $stmt->fetchAll();
But this result in an Array, and all my views was object ready... I`ll need change lots of pages if i query an array.
Can someone help me with this? Thanks!!
Shouldn't it be:
$query = $em->createQuery("SELECT *,
CASE tipodemonstrativo
WHEN 'PB' THEN CONCAT(anoreferencia, '-03-31')
WHEN 'SE' THEN CONCAT(anoreferencia, '-06-30')
WHEN 'SB' THEN CONCAT(anoreferencia, '-09-30')
WHEN 'AN' THEN CONCAT(anoreferencia, '-12-31')
END AS referencia
FROM demonstrativofinanceiro
ORDER BY referencia DESC
LIMIT 4");
$result = $query->getResult();
Try that please.
In Symfony2 it works as
$stmt = $em->getConnection();
$result = $stmt->executeQuery($query)->fetchAll();
I hope it will be helpful
Related
I have following query:
Product::where('shop_id', $shop->id)->with('orderItems')->get()
Product: id | title
OrderItem: id | product_id | sell_price | sold_quantity | sold_date
And i would like to count total income (what is sell_price * sold_quantity) and the same for last 30 days.
How to get all products for shop and calculate that data for every single one.
Thank you.
DB::table('products as p')
->join('orderItems as oi','p.id','oi.product_id')
->where('p.shop_id', $shop->id)
->whereDate('created_at', '>=', Carbon::now()->subDays(30)->toDateTimeString())
->selectRaw('p.id,p.name, sum(oi.sell_price * oi.sold_quantity) as total,
(select sum(sell_price * sold_quantity) from orderItems
where product_id = p.id) as grand_total')
->groupByRaw('p.id,p.name')
->get();
I am trying to do a update a record.
Table name is customer
id | name | address | state
---+---------+------------+-------------------------
1 | John | 123 main st | TX
2 | Jack | 678 John st | NJ
3 | Bet | 987 Tx st | NY
4 | Maddy| 9812 Hudson st | CA
5 | ABCD | 9813 Mainly st | PA
My query is like below
UPDATE CUSTOMER c SET c.state = 'CA' WHERE c.id IN (idList);
Where idList is a localVariable that I created and it returns a list of id like 1,3,5
The query is working if do it like
UPDATE CUSTOMER c SET c.state = 'CA' WHERE c.id IN (1,3,5);
It is updating the respective records to CA.
But if I use it as
UPDATE CUSTOMER c SET c.state = 'CA' WHERE c.id IN (idList);
I get the below error. I don't want to pass the list directly as the list might change. I am getting the list of ids using a different command where it returns and assigns to idList as 1,3,5
Error:
ORA-01722: invalid number
ORA-06512: at line 35
01722. 00000 - "invalid number"**
How to solve this? I am writing it as a stored procedure.
I guess idList is a comma separated string with all the ids that you want to update.So what is happening is that the operator IN compares each id with that string and since this comparison can't succeed in any case you get an error.
What you can do instead is use the LIKE operator:
UPDATE customer
SET "state" = 'CA'
WHERE ',' || idList || ',' LIKE '%,' || "id" || ',%'
See the demo.
You may create parameterized query string and pass values like,
UPDATE CUSTOMER c SET c.state = 'CA' WHERE c.id IN (:idList);
You can't substitute a text variable for a list of values - it's simply not allowed. You're going to have to use dynamic SQL:
EXECUTE IMMEDIATE 'UPDATE CUSTOMER c SET c.state = ''CA'' WHERE c.id IN (' || idList || ')';
I have a table of users
+-------+------+-----+
| User | Sale | Sex |
+-------+------+-----+
| user1 | 120 | M |
| user2 | 98 | M |
| user3 | 5 | F |
+-------+------+-----+
in laravel, we query this by the following statement:
$allMale = UserTable::where('Sex', 'M')->get();
What will happen in I try to query again on the same table
$allFemales = UserTable::where('Sex', 'F')->get();
$user1 = UserTable::where('User', 'user1')->get();
will it query 3 times? is it possible to query once and then Parse it multiple times?
Yes, I'm not sure if UserTable here is Builder or Eloquent but Eloquet under the hood is using MySQL so it will run 3 different queries:
SELECT * FROM users WHERE Sex = 'M';
SELECT * FROM users WHERE Sex = 'F';
SELECT * FROM users WHERE User = 'user1';
Of course you can do it like this:
$users = UserTable::where(function($q) {
$q->whereIn('Sex', ['M', 'F'])->orWhere('User', 'user1')
})->get();
This will generate query:
SELECT * FROM users WHERE ((Sex IN ('M', 'F') OR USER = 'user1'))
and now you can get those users from variable like this using Laravel collection methods:
$allMale = $users->where('Sex', 'M')->get();
$allFemales = $users->where('Sex', 'F')->get();
$user1 = $users->where('User', 'user1')->get();
Now, assuming that user1 has sex set, you could in fact use:
$users = UserTable::whereIn('Sex', ['M', 'F'])->get();
In addition, assuming there is only single user1 instead of:
$user1 = $users->where('User', 'user1')->get();
probably better solution would be:
$user1 = $users->where('User', 'user1')->first();
my table field are
payid payamount paytype
01 5000 1
02 3000 1
03 2500 3
I want to get result as select cash =(select sum (payamount)where paytype=1)
online=(select sum (payamount)where paytype=2)
check=(select sum (payamount)where paytype=3)
how I can do it in codeigniter?
may be you are looking for the following
$this->db->select("SUM(payment)")
->from("TABLE_NAME")
->where("paytype", $paytype)
put the TABLE_NAME and pass the $paytype and hope it will work...
Sounds like a GROUP BY.
SELECT sum(paymount), paytype FROM mytable GROUP BY paytype;
In Codeigniter you can use
$this->db->select_sum('paymount');
$this->db->select('paytype');
$this->db->group_by('paytype');
$query = $this->db->get('mytable');
public function getincomebyyear($s,$e){
$this->db->select('income_id, income_date,income_source,income_sourceid,income_refferanceid,income_description,income_amount,(select sum(income_amount) from tbl_incomes where income_description=1) as cash,'
. '(select sum(income_amount) from tbl_incomes where income_description=2) as online,'
. '(select sum(income_amount) from tbl_incomes where income_description=3) as che');
$this->db->from('tbl_incomes');
$this->db->where('income_date between'
. ' "'. date('Y-m-d', strtotime($s)). '" and'
. ' "'. date('Y-m-d', strtotime($e)).'"');
$query_result= $this->db->get();
$result=$query_result->result();
return $result;
}
I'm working with Eloquent on a One-to-Many relationship.
I want to order my Users by using their last post DateTime (created_at) but I can't figure out how to make this work.
Table Users :
id | name
1 | John
2 | Doe
3 | Foo
4 | ...
Table Posts :
id | title | body | user_id | created_at
1 | Title 1| Body1 | 1 | 2014-03-06 14:00:00
2 | Title 2| Body2 | 1 | 2014-03-04 14:00:00
3 | Title 3| Body3 | 2 | 2014-03-03 14:00:00
4 | Title 4| Body4 | 3 | 2014-03-05 14:00:00
Example of final output desired :
name | title | created_at
John | Title 1 | 2014-03-06 14:00:00
Foo | Title 4 | 2014-03-05 14:00:00
Doe | Title 3 | 2014-03-03 14:00:00
The closer I could get was :
$users = User::with(['posts' => function($query){
$query->orderBy('created_at', 'desc');
}])->get();
But this code extracts all the posts for each user and I just want the last one.
Can you help me please? Thanks.
UPDATE : I finally found what I was looking for : Retrieve users' last post and sort the users in ascending order (of this last post's timestamp). Feel free to improve this query!
$users = DB::table('posts')
->join('users', 'posts.user_id', '=', 'users.id')
->select(DB::raw('posts.id, posts.user_id, MAX(created_at) as created_at'))
->groupBy('posts.user_id')
->orderBy('created_at', 'asc')
->get();
You may try this:
$users = User::with(array('posts' => function($query){
$query->orderBy('created_at', 'desc')->groupBy('user_id');
}))->get();
Update: You may try this:
$users = User::join('posts', 'users.id', '=', 'posts.user_id')
->orderBy('posts.created_at', 'desc')
->groupBy('posts.user_id')
->select('users.*', 'posts.created_at as postTime')
->get();
I've only selected created_at from posts table but you may add more fields in select like:
->select('users.*', 'posts.created_at as postTime', 'posts.updated_at as postUpTime', 'posts.id as pid', 'posts.title')
I believe you will either have to use usort() which is a little bit more complicated, or you can use joins, but with that method, you'd also lose the way Eloquent sets up the relations.
Using usort()...
private function cmp($a, $b)
{
if($a->posts->created_at == $b->posts->created_at) {
return 0;
}
return (strtotime($a->posts->created_at) < strtotime($b->posts->created_at)) ? -1 : 1;
}
$users = User::with(array('posts' => function($query){
$query->orderBy('created_at', 'desc')->groupBy('user_id')->first();
}))->get();
$users = usort($users, array($this, 'cmp'));
Or if you would prefer to use joins, I think this should work for you.
$users = DB::table('posts')
->select(DB::raw('MAX(`posts`.`created_at`) AS `created_at`, `user_id`, `users`.*'))
->orderBy('posts.created_at', 'desc')
->groupBy('posts.user_id')
->join('users', 'users.id', '=', 'posts.user_id')
->get();