I have a query like this
SELECT
`id`,
`advert_id`,
IF(
`chats`.`owner_id` = ?,
`chats`.`sender_id`,
`chats`.`owner_id`
) AS `sender_id`,
IF(
`chats`.`owner_id` = ?,
`chats`.`owner_access_time`,
`chats`.`sender_access_time`
) AS `access_time`,
`created_time`
FROM
`chats`
WHERE 1
AND `id` = ?
AND `owner_id` = ?
AND `project_id` = ?
UNION
SELECT
`id`,
`advert_id`,
IF(
`chats`.`owner_id` = ?,
`chats`.`sender_id`,
`chats`.`owner_id`
) AS `sender_id`,
IF(
`chats`.`owner_id` = ?,
`chats`.`owner_access_time`,
`chats`.`sender_access_time`
) AS `access_time`,
`created_time`
FROM
`chats`
WHERE 1
AND `id` = ?
AND `sender_id` = ?
AND `project_id` = ?
ORDER BY `id` ASC
i am trying to implement it with eloquent query builder like this
$chats = $database
->table('chats')
->where('sender_id', '=', $arguments['user_id'])
->union(
$database
->table('chats')
->where('owner_id', '=', $arguments['user_id'])
->get(
[
'advert_id',
'owner_id',
'sender_id',
'id'
]
)
)
->get(
[
'advert_id',
'owner_id',
'sender_id',
'id'
]
);
But i am getting error Method getBindings does not exist., also i can't find how to write "if" clause with eloquent, all i find is when method, but as far as i understood it works just for "if argument exist, add additional clause to your query", what is not what i need.
Solution
$chats = $database::table('chats')
->where('sender_id', '?')
->select(
'id',
'advert_id',
$database::raw('
IF(
`chats`.`owner_id` = ?,
`chats`.`sender_id`,
`chats`.`owner_id`
) AS `sender_id`
'),
$database::raw('
IF(
`chats`.`owner_id` = ?,
`chats`.`owner_access_time`,
`chats`.`sender_access_time`
) AS `access_time`
')
)
->setBindings(
[
$arguments['user_id'],
$arguments['user_id'],
$arguments['user_id'],
]
)
->union(
$database::table('chats')
->where('owner_id', '?')
->select(
'id',
'advert_id',
$database::raw('
IF(
`chats`.`owner_id` = ?,
`chats`.`sender_id`,
`chats`.`owner_id`
) AS `sender_id`
'),
$database::raw('
IF(
`chats`.`owner_id` = ?,
`chats`.`owner_access_time`,
`chats`.`sender_access_time`
) AS `access_time`
')
)
->setBindings(
[
$arguments['user_id'],
$arguments['user_id'],
$arguments['user_id'],
]
)
)
->get();
Related
I want to do implement a search in the generated data of the sum count of a case when in cakephp with or or conditions in each data.
SELECT `Branches`.`name` AS `Branches__name` , `Branches`.`code` AS `Branches__code` , (
COUNT(
CASE WHEN `prodCarried`.`carried` =1
THEN 1
END )
) AS `carried` , (
COUNT(
CASE WHEN `prodCarried`.`carried` =0
THEN 1
END )
) AS `unCarried`
FROM `branches` `Branches`
INNER JOIN `products_carried_per_branches` `prodCarried` ON ( prodCarried.company_id = Branches.company_id
AND prodCarried.branch_code = Branches.code )
WHERE (
`Branches`.`company_id` =200017
AND `Branches`.`deleted` =0
AND `prodCarried`.`deleted` =0
)
GROUP BY `code`
HAVING COUNT(
CASE WHEN `prodCarried`.`carried` =1
THEN 1
END ) =39
the picture shows the mysql result without the having code
while this is my cakephp code, I want to implement the having sql into cakephp or condition to search the generated sum count or search the data name and code. is this possible or nah
$carriedCase = $query->newExpr()
->addCase(
$query->newExpr()->add(['prodCarried.carried' => '1']),
1,
'integer'
);
$unCarriedCase = $query->newExpr()
->addCase(
$query->newExpr()->add(['prodCarried.carried' => '0']),
1,
'integer'
);
//disctinct code
$query ->select([
'name',
'code',
'carried' => $query->func()->count($carriedCase),
'unCarried' => $query->func()->count($unCarriedCase),
'prodCarried.id',
'prodCarried.validity_start',
'prodCarried.validity_end',
]);
$query ->distinct([
'code'
]);
$query->join([
'prodCarried' => [
'table' =>'products_carried_per_branches',
'type' => 'inner',
'conditions' => [
'prodCarried.company_id = Branches.company_id',
'prodCarried.branch_code = Branches.code',
]
]
]);
$query->where(function (QueryExpression $exp, Query $q) use($option,$search){
$exp->eq('Branches.company_id', $option['company_id']);
$exp->eq('Branches.deleted', 0);
$exp->eq('prodCarried.deleted', 0);
if(!empty($search)){
$orConditions = $exp->or_(function (QueryExpression $or) use ($search) {
$or->like('name', "%$search%");
$or->like('code', "%$search%");
//****************************
return $or;
});
$exp->add($orConditions);
}
return $exp;
});
Depending on your DBMS you can refer to the aggregate of the select list:
$query->having([
'carried' => $searchCount,
]);
Otherwise you have to recreate the aggregate:
$query->having(
function (
\Cake\Database\Expression\QueryExpression $exp,
\Cake\ORM\Query $query
) use (
$carriedCase,
$searchCount
) {
return $exp->eq(
$query->func()->count($carriedCase),
$searchCount
);
}
);
See also
Cookbook > Database Access & ORM > Query Builder > Aggregates - Group and Having
I want to do implement a search in the generated data of the sum count of a case when in cakephp with or or conditions in each data.
SELECT `Branches`.`name` AS `Branches__name` , `Branches`.`code` AS `Branches__code` , (
COUNT(
CASE WHEN `prodCarried`.`carried` =1
THEN 1
END )
) AS `carried` , (
COUNT(
CASE WHEN `prodCarried`.`carried` =0
THEN 1
END )
) AS `unCarried`
FROM `branches` `Branches`
INNER JOIN `products_carried_per_branches` `prodCarried` ON ( prodCarried.company_id = Branches.company_id
AND prodCarried.branch_code = Branches.code )
WHERE (
`Branches`.`company_id` =200017
AND `Branches`.`deleted` =0
AND `prodCarried`.`deleted` =0
)
GROUP BY `code`
HAVING COUNT(
CASE WHEN `prodCarried`.`carried` =1
THEN 1
END ) =39
the picture shows the mysql result without the having code
while this is my cakephp code, I want to implement the having sql into cakephp or condition to search the generated sum count or search the data name and code. is this possible or nah
$carriedCase = $query->newExpr()
->addCase(
$query->newExpr()->add(['prodCarried.carried' => '1']),
1,
'integer'
);
$unCarriedCase = $query->newExpr()
->addCase(
$query->newExpr()->add(['prodCarried.carried' => '0']),
1,
'integer'
);
//disctinct code
$query ->select([
'name',
'code',
'carried' => $query->func()->count($carriedCase),
'unCarried' => $query->func()->count($unCarriedCase),
'prodCarried.id',
'prodCarried.validity_start',
'prodCarried.validity_end',
]);
$query ->distinct([
'code'
]);
$query->join([
'prodCarried' => [
'table' =>'products_carried_per_branches',
'type' => 'inner',
'conditions' => [
'prodCarried.company_id = Branches.company_id',
'prodCarried.branch_code = Branches.code',
]
]
]);
$query->where(function (QueryExpression $exp, Query $q) use($option,$search){
$exp->eq('Branches.company_id', $option['company_id']);
$exp->eq('Branches.deleted', 0);
$exp->eq('prodCarried.deleted', 0);
if(!empty($search)){
$orConditions = $exp->or_(function (QueryExpression $or) use ($search) {
$or->like('name', "%$search%");
$or->like('code', "%$search%");
//****************************
return $or;
});
$exp->add($orConditions);
}
return $exp;
});
Depending on your DBMS you can refer to the aggregate of the select list:
$query->having([
'carried' => $searchCount,
]);
Otherwise you have to recreate the aggregate:
$query->having(
function (
\Cake\Database\Expression\QueryExpression $exp,
\Cake\ORM\Query $query
) use (
$carriedCase,
$searchCount
) {
return $exp->eq(
$query->func()->count($carriedCase),
$searchCount
);
}
);
See also
Cookbook > Database Access & ORM > Query Builder > Aggregates - Group and Having
I have the following SELECT query that looks to if there are records that meet the given criteria:
$stmt = $conn->prepare(' SELECT (`Active`)
FROM `Table1`
WHERE `Name` = ":name" AND Active <> Yes ');
$stmt->execute([
'name' => $_POST['name']
]);
If results of Active could either be a No or just no results. If the results are a No then the following query should run:
$stmt = $conn->prepare('UPDATE `Table1`
SET `active` = `Yes`
WHERE `Name` = `:name`');
$stmt->execute([
'name' => $_POST['name']
]);
If the results of the SELECT query does not find anything then the following query should run:
$stmt = $conn->prepare(' INSERT INTO `Table1` (`Name`,`Active`)
VALUES (:name, :active ) ');
$stmt->execute([
'name' => $_POST['name'],
'active' => $_POST['active']
]);
How can this conditional be written?
I specifically do not want to set a unique constraint to the name column and create stored procedures I need it to be done as a conditional described above.
This should work..
$stmt = $conn->prepare(' SELECT (`Active`)
FROM `Table1`
WHERE `Name` = ":name" AND Active <> Yes ');
$stmt->execute([
'name' => $_POST['name']
]);
if ($stmt->rowCount() === 0) {
$stmt = $conn->prepare(' INSERT INTO `Table1` (`Name`,`Active`)
VALUES (:name, :active ) ');
$stmt->execute([
'name' => $_POST['name'],
'active' => $_POST['active']
]);
} else {
$stmt = $conn->prepare('UPDATE `Table1`
SET `active` = `Yes`
WHERE `Name` = `:name`');
$stmt->execute([
'name' => $_POST['name']
]);
}
I have not tried this one out but it should work. Tell me if it doesnt.
I have MySQL Query i want to write this query zend 2.
select billsec, call_status, Count(*)
from (
select
billsec,
if(ANSWERED_NUM is Null, 'Missed', 'Answered') call_status
from cust_info
where billsec in (
select id
from `users`
where `account_id` = 452 and `added_by` = 20694 and `status` = 'active'
)
)a
group by a.billsec,a.call_status
in zend 2 am trying to write like this but
$adapter = $this->getAdapter();
$resultset = $this->select( function( Select $select ) use ( $request, $adapter ) {
$sub1 = new Select( 'users' );
$sub1->columns( array( 'id' ) );
$sub1->where( array( 'account_id' => '452','added_by' => '20694','status' => 'active' ) );
$sub2 = new Select( 'cust_info' );
$sub2->columns(array("id","billsec", "if(ANSWERED_NUM is Null, 'Missed','Answered')"=>"call_status"));
$sub2->where('billsec IN(?)', new \Zend\Db\Sql\Expression( '?', array( $sub1 ) ));
var_dump( $sub2->getSqlString( $adapter->getPlatform() ) );die();
});
When am print this query output like this:
"SELECT `cust_info`.`id` AS `id`, `cust_info`.`billsec` AS `billsec`, `cust_info`.`call_status` AS `if(ANSWERED_NUM is Null, 'Missed','Answered')` FROM `cust_info` WHERE billsec IN('')"
Here am not able to write IN condition Query, thank in advance.
Sql Query:
SELECT test.* FROM test JOIN test_shares
WHERE test.test_id = test_shares.test_id
AND test_shares.email_address = '$email'
AND test.url is NOT NULL ORDER BY title ASC;
Rewritten as Zend_Db_Select statement.
$select = $db->select ()
->from ( 'test', 'test.*' )
->join ( 'test_shares', array () )
->where ( 'test.test_id = test_shares.test_id')
->where ( 'test_shares.email_address = ?', '$email')
->where ( 'test.url is NOT NULL')
->order ( 'title' );
echo $select;
Output:
SELECT test.* FROM test JOIN test_shares ON Array
WHERE test.test_id = test_shares.test_id
AND test_shares.email_address = '$email'
AND test.url is NOT NULL ORDER BY title ASC
Please suggest why this 'ON Array' is showing.
Try this:
$select = $db ->select ()
->from ( 'movie', 'movie.*' )
->join(array('movie_shares'), 'movie.movie_id = movie_shares.movie_id');
->where ( 'movie_shares.email_address = ?', '$email')
->where ( 'movie.url is NOT NULL')
->order ( 'title' );
echo $select;
You're supplying an array where a string is expected for the ON clause, so PHP literally prints array() instead of the string.