i want to use result of findall which is array in condition of cactivedataprovider ?
$criteria->condition = 'department_id=:email';
$criteria->params = array(':email'=>$id);
$subject_ids=subject::model()->findAll($criteria);
public function myDataProvider($subject_ids)
{
foreach($subject_ids as $value){
print_r($value);
foreach($value as $val){
echo $val;
}
}
$dataProvider=new CActiveDataProvider('Lecture', array(
'criteria'=>array(
'condition'=>'subject_id='+$val,
)
));
return $dataProvider;
}
how i should use the array has multy rows
You function should looks like
public function myDataProvider($subject_ids)
{
$criteria = new CDbCriteria;
$criteria->compare('subject_id=', $subject_ids);
$dataProvider=new CActiveDataProvider('Lecture', array(
'criteria'=>$criteria
));
return $dataProvider;
}
But $subject_ids is not array of int in your example, so you can do that:
$ids = CHtml::listData(subject::model()->findAll($criteria), 'id', 'id');
and you will get ids.
Related
I want to find if a $work (string) exist in Works (array), how can I write the request?
public function findByProject($project, $work)
{
return $this->createQueryBuilder('p')
->andWhere('p.project_type = :project')
->andWhere('p.works = :work')
->setParameter('project', $project)
->setParameter('work', $work)
->orderBy('p.id', 'ASC')
//->setMaxResults(10)
->getQuery()
->getResult()
;
}
public function findByProject($project, $work)
{
return $this->createQueryBuilder('p')
->andWhere('p.project_type = :project')
->andWhere('p.works LIKE :work')
->setParameter('project', $project)
->setParameter('work', '%'.$work.'%')
->orderBy('p.id', 'ASC')
//->setMaxResults(10)
->getQuery()
->getResult()
;
}
I have the following controller
/**
*
* #Route("/searchname" , name="search_student_name")
*
*/
public function SearchStudentName(Request $request, SessionInterface $sessionName)
{
$params = $request->request->all();
$SName = $params['txtSearchName'];
if (isset($SName)){
$sessionName->set('SName', $SName);
}
$em = $this->getDoctrine()->getManager();
$query = $em->createQuery("SELECT s FROM AppBundle:Student s WHERE s.name LIKE :Name ORDER BY s.name");
$query->setParameter('Name', '%'.$sessionName->get('SName').'%');
$students = $query->getArrayResult();
$paginator = $this->get('knp_paginator');
$result = $paginator->paginate(
$students,
$request->query->get('page', 1)/*page number*/,
50/*limit per page*/
);
return $this->render('student/index.html.twig', array(
'students' => $result,
));
}
The first page was displayed correctly.
But When I am trying to go to other page
app_dev.php/student/searchname?page=2
I have the following error:
NotFoundHttpException
HTTP 404 Not Found
AppBundle\Entity\Student object not found by the #ParamConverter annotation.
I have the indexAction which works fine for any page:
the only difference is $students = $em->getRepository('AppBundle:Student')->findAll();
and the use of session to save the name
/**
* Lists all student entities.
*
* #Route("/", name="student_index")
* #Method("GET")
*/
public function indexAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$students = $em->getRepository('AppBundle:Student')->findAll();
/**
* #var $paginator \Knp\Component\Pager\Paginator
*/
$paginator = $this->get('knp_paginator');
$result = $paginator->paginate(
$students,
$request->query->get('page', 1)/*page number*/,
50/*limit per page*/
);
return $this->render('student/index.html.twig', array(
'students' => $result,
));
}
Can someone help me how to solve this issue?
Session value
Maybe $sessionName->get('SName') is empty or null ?, you can try put a default value for the session like this:
$sessionName->get('SName', 'something default');
I've got this table
beds
id
name
size
room
status
hotel
created_at
updated_at
I need to filter all beds that belong to a certain room. In order to do so, I've coded this lines.
public function index()
{
//
$user = JWTAuth::parseToken()->authenticate();
$data = Input::get('room');
if( $data ){
$beds = Bed::where('room', '=', $data )->get();
}else{
$beds = Bed::where('hotel', '=', $user->hostel )->get();
}
foreach( $beds as $bed) {
return $bed->get( array('size','room', 'id') );
}
}
So, If i give it the room id, it should return me only that room's ones.
The thing is that it's returning all table entries.
Any ideas?
UPDATE
Fixed relations and tried this:
return Room::with('beds')->findOrFail($data)->beds;
Now it gives me the number of items.
How can I get the items?
UPDATE
This is the model's code:
class Room extends \Eloquent {
protected $fillable = array('beds', 'price', 'name', 'description','hotel');
public function beds(){
return $this->hasMany('Bed', 'id', 'room');
}
}
UPDATE
The var_dump for:
var_dump( Room::with('beds')->findOrFail($data)->beds );
is:
int(1)
UPDATE
So, the final code is the following.
controller
public function index()
{
//
$user = JWTAuth::parseToken()->authenticate();
$data = Input::get('room');
if( $data ){
$d = intval( $data );
return Bed::where('room', '=', $d )->get( array('size', 'room', 'id', 'name') );
}else{
return Bed::where('hotel', '=', $user->hostel )->get( array('size', 'room', 'id', 'name') );
}
}
model
class Room extends \Eloquent {
protected $fillable = array('beds', 'price', 'name', 'description','hotel');
public function camas(){
return $this->hasMany('Bed', 'room', 'id');
}
}
Thank you guys!
You have quite a few issues in your attempts:
return $bed->get( array('size', 'room', 'id') );
// runs SELECT size, room, id from `rooms`
so it returns all the rooms (why on earth would you like to do this in a foreach anyway?)
return $this->hasMany('Bed', 'id', 'room');
// should be:
return $this->hasMany('Bed', 'room', 'id');
protected $fillable = array('beds', ...
public function beds(){
this is conflict - you will never get a relations when calling $room->beds since you have a column beds on your table.
that said, this is what you need:
public function index()
{
$user = JWTAuth::parseToken()->authenticate();
if(Input::has('room')){
$query = Bed::where('room', '=', Input::get('room'));
}else{
$query = Bed::where('hotel', '=', $user->hostel);
}
return $query->get(['size', 'room', 'id']); // given you need only these columns
}
Try this and see if it works. If not, can you provide the var_dump of Input::get('room') and the structure of the the beds table?
public function index()
{
//
$user = JWTAuth::parseToken()->authenticate();
$data = Input::get('room');
if( $data ){
$beds = Bed::where('room', '=', $data );
}else{
$beds = Bed::where('hotel', '=', $user->hostel );
}
return $beds->get(['size','room', 'id'])->toArray();
}
Better yet if you want to get specific beds in a room and you have your relations set up correctly:
return Room::with('beds')->findOrFail($data)->beds;
EDIT
I saw your update. Are you sure its giving you a number of items, maybe there is one item and the number is the id of it. Can you verify? Please provide a vardump of it if thats not the case. Also can you post your code for the relations in the model?
Is it possible to extract raw sql query from the query builder instance in Phalcon? Something like this?
$queryBuilder = new Phalcon\Mvc\Model\Query\Builder();
$queryBuilder
->from(…)
->where(…);
$rawSql = $queryBuilder->hypotheticalGetRawQueryMethod();
By error and trial the below seems to working. Would be great if someone could confirm if there's a better way.
$queryBuilder = new Builder();
$queryBuilder->from(…)->where(…);
$intermediate = $queryBuilder->getQuery()->parse();
$dialect = DI::getDefault()->get('db')->getDialect();
$sql = $dialect->select($intermediate);
Edit: As of 2.0.3 you can do it super simple, see comment for full details:
$modelsManager->createBuilder()
->from('Some\Robots')
->getQuery()
->getSql()
you can use getRealSqlStatement() (or similar function name) on the DbAdapter. See http://docs.phalconphp.com/en/latest/api/Phalcon_Db_Adapter.html
According to documentation you can get this way the resulting sql query.
Or wait, this might not work on querybuilder. Otherwise you can setup low level query logging: http://docs.phalconphp.com/en/latest/reference/models.html#logging-low-level-sql-statements
$db = Phalcon\DI::getDefault()->getDb();
$sql = $db->getSQLStatement();
$vars = $db->getSQLVariables();
if ($vars) {
$keys = array();
$values = array();
foreach ($vars as $placeHolder=>$var) {
// fill array of placeholders
if (is_string($placeHolder)) {
$keys[] = '/:'.ltrim($placeHolder, ':').'/';
} else {
$keys[] = '/[?]/';
}
// fill array of values
// It makes sense to use RawValue only in INSERT and UPDATE queries and only as values
// in all other cases it will be inserted as a quoted string
if ((strpos($sql, 'INSERT') === 0 || strpos($sql, 'UPDATE') === 0) && $var instanceof \Phalcon\Db\RawValue) {
$var = $var->getValue();
} elseif (is_null($var)) {
$var = 'NULL';
} elseif (is_numeric($var)) {
$var = $var;
} else {
$var = '"'.$var.'"';
}
$values[] = $var;
}
$sql = preg_replace($keys, $values, $sql, 1);
}
More you can read there
The following is the common solution:
$result = $modelsManager->createBuilder()
->from(Foo::class)
->where('slug = :bar:', ['bar' => "some-slug"])
->getQuery()
->getSql();
But you might not expect to see the query without its values, like in:
die(print_r($result, true));
Array
(
[sql] => SELECT `foo`.`id`, `foo`.`slug` FROM `foo` WHERE `foo`.`slug` = :bar
[bind] => Array
(
[bar] => some-slug
)
[bindTypes] =>
)
So, this simple code might be useful:
public static function toSql(\Phalcon\Mvc\Model\Query\BuilderInterface $builder) : string
{
$data = $builder->getQuery()->getSql();
['sql' => $sql, 'bind' => $binds, 'bindTypes' => $bindTypes] = $data;
$finalSql = $sql;
foreach ($binds as $name => $value) {
$formattedValue = $value;
if (\is_object($value)) {
$formattedValue = (string)$value;
}
if (\is_string($formattedValue)) {
$formattedValue = sprintf("'%s'", $formattedValue);
}
$finalSql = str_replace(":$name", $formattedValue, $finalSql);
}
return $finalSql;
}
If you're using query builder then like given below then getPhql function can serve the purpose as per phalcon 3.4.4 version.
$queryBuilder = new Builder();
$queryBuilder->from(…)->where(…)->getQuery();
$queryBuilder->getPhql();
if (!function_exists("getParsedBuilderQuery")) {
/**
* #param \Phalcon\Mvc\Model\Query\BuilderInterface $builder
*
* #return null|string|string[]
*/
function getParsedBuilderQuery (\Phalcon\Mvc\Model\Query\BuilderInterface $builder) {
$dialect = Phalcon\Di::getDefault()->get('db')->getDialect();
$sql = $dialect->select($builder->getQuery()->parse());
foreach ($builder->getQuery()->getBindParams() as $key => $value) {
// For strings work fine. You can add other types below
$sql = preg_replace("/:?\s?($key)\s?:?/","'$value'",$sql);
}
return $sql;
}
}
Simple function that im using for debugging.
How to get an array by Executing this query in Yii?
SELECT `sevrity_id`,COUNT(*) FROM `Incident` GROUP BY `sevrity_id`
I need an array like this: array(1=>20,2=10,3=12)
public function getSevrityCounts()
{
$data = array();
$command = Yii::app()->db->createCommand('SELECT sevrity_id,COUNT(*) AS num FROM Incident GROUP BY sevrity_id');
foreach($command->queryAll() as $row) {
$data[ $row['sevrity_id'] ] = $row['num'];
}
return $data;
}