How to make a query based on a view? - phalcon

The standard way to make a query against a database table is to create a model and create a function within it , for example :
<?php
use Phalcon\Mvc\Model;
use Phalcon\Mvc\Model\Query;
class Client extends Model {
function lireParCritere($critere) {
$sSQL = "
SELECT c.clt_id as clt_id,c.clt_cin_pass,c.clt_nom,c.clt_prenom,c.clt_tel,
c.clt_adresse,c.clt_comment,CONCAT_WS(
' ',
c.clt_nom,
c.clt_prenom
) AS noms
FROM Client as c WHERE 1 = 1 ";
if(isset($critere["clt_id"]) && $critere["clt_id"] != "") {
$sSQL .= "AND c.clt_id = '" . $critere["clt_id"] . "' ";
}
$sSQL .= " ORDER BY noms";
$query = new Query($sSQL,$this->getDI());
$ret = $query->execute();
return $ret;
}
}
?>
What is the way to make a query against a database view ?

A database view is basically the output of a SQL query stored in another table. You can think of a view as an alias for a specific SQL query that you can then run other queries on top of. (kind of like SELECT * FROM (SELECT * FROM table_one, table_two, table_n);)
This means that you can treat the view as a regular table and pull from it without any issues.
So lets say you have a database view that has three columns id, col_one, col_two. You could do something similar to the following.
<?php
/**
* Model representing the database view
*/
class Example extends \Phalcon\Mvc\Model
{
public $id;
public $col_one;
public $col_two;
public function getSource()
{
return 'view_name_in_database';
}
public function columnMap()
{
return array(
'id' => 'id',
'col_one' => 'col_one',
'col_two' => 'col_two'
);
}
}
// example query on the model
$examples = Example::query()
->where('id = :id:')
->bind(array(
'id' => 55
))->execute();
?>

Related

TYPO3 Repository outside controller

I am using TYPO3 10.4.15 and try to write a TcaProcFunc for my own extension.
namespace HGA\Album\UserFunc;
use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Extbase\Object\ObjectManager;
use HGA\Album\Domain\Repository\AlbumRepository;
use HGA\Album\Domain\Model\Album;
use TYPO3\CMS\Extbase\Persistence\PersistenceManagerInterface;
class TcaProcFunc
{
/**
* #param array $config
*
*/
public function getLink(&$config)
{
$ret = [];
$objectManager = GeneralUtility::makeInstance(ObjectManager::class);
$albumRepository= $objectManager->get(AlbumRepository::class);
$albums = $albumRepository->findAll();
foreach ($albums as $album){
$ret[] = ["Test1","Test1"];
}
$i = count($albums);
error_log("Album: " . $i, 0 );
$ret[] = ["Test", "Test"];
$config['items'] = $ret;
// error_log("UserFunc: " . var_export($config, true), 0);
}
}
The problem is, that findall() does not provide any result. $albumsis empty, but there is one record inside the database.
HGA is my vendor name and Album the extension name. The TcaProcFunc is in generell is working, but I don't have any access to the extension database.
Can anybody tell me, what is wrong with my code or how I what I can do to findthe problem?
Thank you in advance.
Finally I did it with ConnectionPool
namespace HGA\Album\UserFunc;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Extbase\Object\ObjectManager;
use TYPO3\CMS\Core\Database\ConnectionPool;
class TcaProcFunc
{
/**
* #param array $config
*
*/
public function getLink(&$config)
{
$ret = [];
$albums = GeneralUtility::makeInstance(ConnectionPool::class)
->getConnectionForTable('tx_album_domain_model_album')
->select(
['uid', 'album_artist', 'album'],
'tx_album_domain_model_album',
[]
)->fetchAll();
foreach ($albums as $album){
$ret[] = [$album['album_artist'] . ": " . $album['album'], $album['uid']];
}
$config['items'] = $ret;
}
}

Laravel where query not working

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?

Get raw sql from Phalcon query builder

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.

Zend/db/Sql/ query syntax

I am starting with Zend Framework 2 , I want to make a routing choice with the role of My user and I must write getRoleByID($id) ,
then
How can'I write
" Select 'role' from user where ('id' = $id) " with Zend\Db\Sql
Example Using Select:
$select = new \Zend\Db\Sql\Select('user');
$select->columns(array('role'));
$where = new Where();
$where->equalTo('id', $id);
$select->where($where);
/**
* Simple example of executing a query...
*/
$stmt = $this->getSql()->prepareStatementForSqlObject($select);
$results = $stmt->execute();
/* #var $results \Zend\Db\Adapter\Driver\Pdo\Result */
if( ! $results->count()) {
// do something, none found...
}
$row = $results->current();
return $row['role'];
// if you had multiple results to iterate over:
//$resultSet = new \Zend\Db\ResultSet\ResultSet();
//$resultSet->initialize($results);
//$array = $resultSet->toArray();
//foreach($resultSet as $row) { /* ... */ }

How can i load model in joomla?

This is my Controller
// No direct access
defined( '_JEXEC' ) or die( 'Restricted access' );
jimport('joomla.application.component.controller');
/**
* Hello World Component Controller
*
* #package Joomla.Tutorials
* #subpackage Components
*/
class HelloController extends JController
{
/**
* Method to display the view
*
* #access public
*/
function __construct($default = array())
{
parent::__construct($default);
// Register Extra tasks
$this->registerTask( 'detail' , 'display' );
}
function display()
{
switch($this->getTask())
{
case 'detail' :
{
JRequest::setVar( 'view' , 'new');
// Checkout the weblink
$model = $this->getModel('hello');
} break;
}
parent::display();
}
}
this is my view.html.php
class HelloViewNew extends JView
{
function display($tpl = null)
{
global $mainframe;
$db =& JFactory::getDBO();
$model =& $this->getModel('hello');
$items = & $model->getdetail();
$this->assignRef( 'items', $items );
parent::display($tpl);
}
}
and this is my model
defined( '_JEXEC' ) or die( 'Restricted access' );
jimport( 'joomla.application.component.model' );
/**
* Hello Model
*
* #package Joomla.Tutorials
* #subpackage Components
*/
class HelloModelHello extends JModel
{
/**
* Gets the greeting
* #return string The greeting to be displayed to the user
*/
var $_data;
/**
* Returns the query
* #return string The query to be used to retrieve the rows from the database
*/
function _buildQuery()
{
$query = ' SELECT * '
. ' FROM #__hello WHERE published = 1'
;
return $query;
}
/**
* Retrieves the hello data
* #return array Array of objects containing the data from the database
*/
function getData()
{
// Lets load the data if it doesn't already exist
if (empty( $this->_data ))
{
$query = $this->_buildQuery();
$this->_data = $this->_getList( $query );
}
//echo "<pre>"; print_r($this->_data); exit;
return $this->_data;
}
function detail()
{
echo "this is test"; exit;
}
}
My question is how can i fetch that detail function from database its not working for me?
on your model, you've the function : function detail() ,
But you've tried to call the function on view with : $items = & $model->getdetail();
Remember your function is detail() NOT getdetail() . So, call with :
$items = & $model->detail();
That's your only mistake I guess so, good luck
you should use this in contoller
$view = $this->getView();
$view->setModel($this->getModel());
then you can use $this->getModel() in view.