TYPO3 Extbase Join - sql

I'm try to make this query with extbase work:
SELECT a.*
FROM tx_apartments_domain_model_apartment a
LEFT
JOIN tx_apartments_domain_model_booking b
ON b.apartment = a.uid
AND b.start <= '2018-07-23'
AND b.end >= '2018-07-21'
WHERE b.uid IS NULL AND a.hidden=0 AND a.deleted=0;
the following code does not work, i get an empty result:
/** #var QueryBuilder $queryBuilder */
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
->getQueryBuilderForTable('tx_apartments_domain_model_apartment');
$statement = $queryBuilder
->select('a.*')
->from('tx_apartments_domain_model_apartment','a')
->leftJoin(
'a',
'tx_apartments_domain_model_booking',
'b',
$queryBuilder->expr()->andX(
$queryBuilder->expr()->eq('b.apartment','a.uid'),
$queryBuilder->expr()->lte('b.start', '2018-07-23'),
$queryBuilder->expr()->gte('b.end', '2018-07-21')
)
)
->where(
$queryBuilder->expr()->isNull('b.uid')
)
->execute();
//DebuggerUtility::var_dump($queryBuilder->getSQL());
return $statement->fetchAll();
can anybody help me?

What kind of records do you expect to get?
as uid is a mandantory field you never have records where the uid is NULL.
If you want to access new records which are not stored to the database yet: they get a faked uid like NEW123

This works for me:
/** #var QueryBuilder $queryBuilder */
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
->getQueryBuilderForTable('tx_apartments_domain_model_apartment');
$queryBuilder
->getRestrictions()
->removeAll();
$statement = $queryBuilder
->select('a.*')
->from('tx_apartments_domain_model_apartment','a')
->leftJoin(
'a',
'tx_apartments_domain_model_booking',
'b',
$queryBuilder->expr()->andX(
$queryBuilder->expr()->eq('b.apartment','a.uid'),
$queryBuilder->expr()->lte('b.start', $queryBuilder->createNamedParameter('2018-07-23')),
$queryBuilder->expr()->gte('b.end', $queryBuilder->createNamedParameter('2018-07-21'))
)
)
->where(
$queryBuilder->expr()->andX(
$queryBuilder->expr()->isNull('b.uid'),
$queryBuilder->expr()->eq('a.hidden',0),
$queryBuilder->expr()->eq('a.deleted',0)
)
)
->execute();
$results = $statement->fetchAll();
// DebuggerUtility::var_dump($queryBuilder->getSQL());
// DebuggerUtility::var_dump($results);
return $results;

I do not know where exactly you are using this code. Typically I would think that retrieving records from the database should happen in a repository.
If you are using this in the ApartmentRepository and if there is a relation properly configured between apartments and bookings (1:n, I would assume) in the TCA, then you could use something like this:
public function findInDateRange ($dateConstraint)
{
$query = $this->createQuery();
$constraints = [];
$constraints[] = $query->lessThanOrEqual(
'bookings.start',
$dateConstraint['start']
);
$constraints[] = $query->greaterThanOrEqual(
'bookings.end',
$dateConstraint['end']
);
$query->matching($query->logicalAnd($constraints));
return $query->execute();
}
I deliberately left out the b.uid IS NULL part here, as that should always return nothing since uid should be AUTO_INCREMENT. Unless the default query settings are changed, there is also no need to check the disable fields (hidden, deleted) manually.
Note that in order for this to work, the Apartment Domain Model needs a field bookings with a corresponding column in the database (that is something I stumbled over last year).
As a side-note: Is it intentional that you allow for the end to be before the start in your query (start: 2018-07-23, end: 2018-07-21), or is that just exemplary?

Related

$queryBuilder->createNamedParameter in update query not working (TYPO3 10.4)

In a custom utility class (no controller or repository) I have the following UPDATE-Query:
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('my_table');
$uid = 1;
$val = 'Test';
$queryBuilder
->update('my_table')
->set('title', $queryBuilder->createNamedParameter($val))
->where(
$queryBuilder->expr()->eq('uid', $uid)
)
->execute();
When the update is done, the title in the database record has the value ":dcValue1" and not "Test".
Why does the prepared statement not resolve the parameter $val?

Get user data from database codeignter

I have two tables in one database, table one called: ci_admin, and table two called active_ingredient.
I want to get user data from the active_ingredient table where user_id equals admin_id from ci_admin table using the current user session.
this code, get data for all user, I need the data inserted by the user only:
$wh =array();
$SQL ='SELECT * FROM active_ingredient';
$wh[] = "SELECT 1
FROM ci_admin
WHERE ci_admin.admin_id = active_ingredient.user_id";
if(count($wh)>0)
{ $WHERE = implode(' and ',$wh);
return $this->datatable->LoadJson($SQL,$WHERE);
}
else
{
return $this->datatable->LoadJson($SQL);
}
Try this, it will help you.
$this->db->select('ai.*,ca.*');
$this->db->from('active_ingredient ai');
$this->db->join('ci_admin ca', 'ca.admin_id = ai.user_id', 'left');
$this->db->where($data); //pass the session data for exact filter
$query = $this->db->get();
return $query->result();

Yii left join query

I want to execute the below sql query using Yii framework and need help on this.
SQL query
SELECT t.*, LP.name AS lp_name FROM `user` AS `t` LEFT JOIN `level_profiles` AS `LP` ON t.prof_i = LP.id WHERE t.bld_i IN (17)
So, i tried the below steps.
$usql = 't.bld_i IN (17)';
$criteria1 = new CDbCriteria;
$criteria1->select = 't.*, LP.*';
$criteria1->join = ' LEFT JOIN `level_profiles` AS `LP` ON t.prof_i = LP.id';
$criteria1->addCondition($usql);
$criteria1->order = 't.prof_i';
$result = User::model()->findAll($criteria1);
The above step is not allowing me to access the value from 'level_profiles' table.
Then, i tried to execute:
$usql = 't.bld_i IN (17)';
$result = User::model()->with('level_profiles', array(
'level_profiles'=>array(
'select'=>'name',
'joinType'=>'LEFT JOIN',
'condition'=>'level_profiles.id="prof_i"',
),
))->findAll($usql);
This is returning an error 'Relation "level_profiles" is not defined in active record class "User". '
I know this could be executed using the below method.
Yii::app()->db->createCommand('SELECT query')->queryAll();
But i dont want to use the above.
I am a beginner with Yii and tried to look into the forums. But, i am getting confused how to execute the query using "User::model()" approach .
class User extends CActiveRecord
{
......
public function relations()
{
return array(
'level_porfile_relation'=>array(self::BELONGS_TO, 'Level_Profiles_Modelname', 'prof_i'),
);
}
and your query will be:
$result = User::model()->with('level_porfile_relation')->findAll($usql);

Codeigniter Joining Tables - Passing Parameters

I'm attempting to join two tables while using codeigniter. I've done this same SQL query writing regular SQL. When I attempt to do the same in codeigniter, I keep getting errors. I'm not quite sure what I'm doing wrong. What do you guys think I'm doing wrong?
My function in model_data.php
function getJoinInformation($year,$make,$model)
{
//$this->db->distinct();
// here is where I need to conduct averages but lets just work on extracting info.
// from the database and join tables.
$this->db->select('*');
$this->db->from('tbl_car_description');
$this->db->join('tbl_car_description', 'd.id = p.cardescription_id');
$this->db->where('d.year', $year);
$this->db->where('d.make', $make);
$this->db->where('d.model', $model);
$result = $this->db->get();
/*
$query = $this->db->get_where('tbl_car_description',
array(
'year' => $year,
'make' => $make,
'model' => $model
)
);
if($query->num_rows()) return $query->result();
return null;
*/
}
My error message
A Database Error Occurred
Error Number: 1066
Not unique table/alias: 'tbl_car_description'
SELECT * FROM (`tbl_car_description`) JOIN `tbl_car_description` ON `d`.`id` = `p`.`cardescription_id` WHERE `d`.`year` = '2006' AND `d`.`make` = 'Subaru' AND `d`.`model` = 'Baja'
Filename: C:\wamp\www\_states\system\database\DB_driver.php
Line Number: 330
Here is the code written in SQL and it's working great. I want to do the something in codeigniter but I'm confused as to how. Any help would be much appreciated. Thanks everyone.
$sql_2 = mysql_query("SELECT ROUND(AVG(p.value),1) AS AvgPrice, ROUND(AVG(p.mileage),1) AS AvgMileage
FROM tbl_car_description d, tbl_car_prices p
WHERE (d.id = p.cardescription_id)
AND (d.year = '".$year."')
AND (d.make = '".$make."')
AND (d.model = '".$model."')
AND (p.approve = '1')");
Your CI query references the same table twice, which I assume is a typo. However, you only need include your table alias with the table name in your Active Record call:
//$this->db->distinct();
$this->db->select('*');
$this->db->from('tbl_car_description d');
$this->db->join('tbl_car_prices p', 'd.id = p.cardescription_id');
$this->db->where('d.year', $year);
$this->db->where('d.make', $make);
$this->db->where('d.model', $model);
$result = $this->db->get();
Couple issues: You need to include your table aliases and your join should have the name of the second table ...
$this->db->from('tbl_car_description AS d');
$this->db->join('tbl_car_prices AS p', 'd.id = p.cardescription_id');

How to get particular column in zend using Left join

I am new to zend framework,
Following is the plain mysql query which takes particular column from table,
SELECT jobs_users.id,jobs_users.first_name from jobs_users left join friends on jobs_users.id=friends.friend_id where friends.member_id=29
I tried with zend to implement the above query like below,
public function getFriendsProfileList($id){
$db = Zend_Db_Table::getDefaultAdapter();
$select = $db->select();
$select->from('jobs_users')
->joinLeft(
'friends',
'jobs_users.id=friends.friend_id',
array('jobs_users.id','jobs_users.first_name','jobs_users.last_name','jobs_users.photo')
)
->where("friends.member_id = ?", $id);
$result = $db->fetchAll($select);
return $result;
}
Here i got result with all column name , not with exact column name which i have given in query.
Kindly help me on this.
Use this instead:
$select->from('jobs_users', array('jobs_users.id','jobs_users.first_name','jobs_users.last_name','jobs_users.photo'))
->joinLeft('friends', 'jobs_users.id=friends.friend_id')
->where("friends.member_id = ?", '20');
You may also try this:
$select = $db->select();
$select->setIntegrityCheck(false);
$select->joinLeft('jobs_users','',array('jobs_users.id','jobs_users.first_name','jobs_users.last_name','jobs_users.photo'));
$select->joinLeft('friends','jobs_users.id=friends.friend_id', array());
$select->where("friends.member_id = ?", $id);
$result = $db->fetchAll($select);
return $result;