Find conditions like 'NOT EXISTS' - mysql

I have 2 tables in my db...
Entita
id int(11)
descrizione varchar(50)
.....
Publicobjects
....
model varchar(50) the model I need (in this case 'Entita')
model_id int(11)
I would like to make a query like this:
select entita.*
from entita
where NOT EXISTS (select * from publicobjects where publicobjects.model = 'Entita' and publicobjects.model_id = entita.id)
How can I do this with the model functions of Cakephp without use custom query?
Thanks

I believe you're trying to find rows from the Entita table that are not in the Publicobjects table. Assuming that is correct, here is the SQL query for MySQL to find it:
SELECT `entita`.*
FROM `entita`
LEFT JOIN `publicobjects` ON (`publicobjects`.`model` = 'entita'
AND `publicobjects`.`model_id` = `entita`.`id`)
WHERE `publicobjects`.`model_id` IS NULL
To make this work with CakePHP's models takes a couple of steps. I've made some assumptions about your model names, but I could be wrong and those are easy to fix.
First add this to the Entita model:
<?php
var $hasOne = array('Publicobject' => array(
'foreignKey' => 'model_id',
'conditions' => 'Publicobject.model = "Entita"'));
Now, you can check for entries that are missing in the Publicobjects table like this:
<?php
$this->Entita->find('all', array('conditions' => array('Publicobject.model_id IS NULL')));

Related

How to use AND and OR in MySQL query?

I want to get those records whose date_last_copied field is empty or less than the current date. I tried this, but it did not give me the desired result:
$tasks = $this->Control->query("
SELECT *
FROM
`controls`
WHERE
`owner_id` = ".$user_id."
AND `control_frequency_id` = ".CONTROL_FREQUENCY_DAILY."
OR `date_last_copied` = ''
OR `date_last_copied` < ". strtotime(Date('Y-m-d'))."
");
Current query looks something like this, I think. That is, find the records with the correct owner_id and frequency_id, where the date_last_copied is null or less than a certain date. Is that logic correct?
SELECT *
FROM controls
WHERE owner_id = ::owner_id::
AND control_frequency_id = ::frequency_id::
AND (
date_last_copied IS NULL
OR date_last_copied < ::date::
)
But we should really be using the CakePHP query builder, rather than running raw SQL. This article gives some details. If I were to take a stab at a solution, we'd want something like the following. But we ideally want someone from the CakePHP community to chime in here. EDIT: Note that this seems to be for CakePHP 3.0, only.
// Build the query
$query = TableRegistry::get('controls')
->find()
->where([
'owner_id' => $ownerId,
'control_frequency_id' => $frequencyId,
'OR' => [
['date_last_copied IS' => null],
['date_last_copied <' => $date]
]
]);
// To make sure the query is what we wanted
debug($query);
// To get all the results of the query
foreach ($query as $control) {
. . .
}
I'm suggesting this, rather than the raw SQL string you have above, because:
We can now leverage the ORM model of CakePHP.
We don't have to worry about SQL injection, which you're currently vulnerable to.
EDIT: OK, this is a guess at the syntax applicable for CakePHP 2.0... YMMV
$controls = $this->controls->find('all', [
'conditions' => [
'owner_id' => $ownerId,
'control_frequency_id' => $frequencyId,
'OR' => [
['date_last_copied IS' => null],
['date_last_copied <' => $date]
]
]
];
Otherwise, we just use the raw query as a prepared statement:
$result = $this->getDataSource()->fetchAll("
SELECT *
FROM controls
WHERE owner_id = ?
AND control_frequency_id = ?
AND (
date_last_copied IS NULL
OR date_last_copied < ?
)",
[$ownerId, $frequencyId, $date]
);
Not sure about your whole logic but your final query statement should be something like:
SELECT * FROM `controls` WHERE (`owner_id` = <some owner_id>)
AND (`control_frequency_id` = <some id value>)
AND (`date_last_copied` = '' OR
`date_last_copied` IS NULL OR
`date_last_copied` < CURDATE() )
Use parentheses carefully to match your logic.
Always specify the version of cakePHP you are using for your App.
This query should work fine in CakePHP 3.0 for SQL AND and OR.
$query = ModelName>find()
->where(['colunm' => 'condition'])
->orWhere(['colunm' => 'otherCondition'])
->andWhere([
'colunm' => 'anotherContion',
'view_count >' => 10
])
->orWhere(['colunm' => 'moreConditions']);

DB Selecting from multiple table with join using alias in Yii2

I am trying to do a check against 3 table that I join together. I do not want to use the real table name hard coded as my project is highly under develop and table prefix may be changed. What is the best way in Yii2 to select from 3 table where I have where statement on the joined table?
I can get what I want from the code below. But as I said, I do not want to use the table alias hard coded. Any idea how to fix this or suggestion of other ideas would be very appreciated.
$userId = Yii::$app->user->id;
$result = \app\models\UserPermission::find()->joinWith([
'permission',
'permission.service'
])->where([
'prefix_user_permission.user_id' => $userId,
'prefix_permission.flag' => Permission::LOGIN,
'prefix_service.login_available' => Service::LOGIN_AVAIABLE,
])->all();
I would like to end up with this query:
SELECT *
FROM `prefix_user_permission` `up`
INNER JOIN `prefix_permission` `p` ON `up`.`permission_id` = `p`.`id`
INNER JOIN `prefix_service` `s` ON `p`.`service_id` = `s`.`id`
WHERE (`up`.`user_id`=43)
AND (`p`.`flag`='LOGIN')
AND (`s`.`login_available`=1);
The table prefix can be configured using the 'tablePrefix' param along with the main db config as follows:
'components' => [
'db' => [
//other db config params
'tablePrefix' => 'pre_'
]
This prefix can be used as follows:
There's a special variant on this syntax specific to tablenames: {{%Y}} automatically appends the application's table prefix to the provided value, if a table prefix has been set:
$sql = "SELECT COUNT([[$column]]) FROM {{%table}}";
$rowCount = $connection->createCommand($sql)->queryScalar();
Or if you are using active record for models then you can also use the tableName() function to replace the hard-coded table names.

MYSQL fetch records from table 1 that do not exist in table 2

I created a php function to fetch records from a sql table subscriptions, and I want to add a condition to mysql_query to ignore the records in table subscriptions that exists in table removed_items, here is my code;
function subscriptions_func($user_id, $limit){
$subs = array();
$sub_query = mysql_query("
SELECT `subscriptions`.`fo_id`, `subscriptions`.`for_id`, `picture`.`since`, `picture`.`user_id`, `picture`.`pic_id`
FROM `subscriptions`
LEFT JOIN `picture`
ON `subscriptions`.`fo_id` = `picture`.`user_id`
WHERE `subscriptions`.`for_id` = $user_id
AND `picture`.`since` > `subscriptions`.`timmp`
GROUP BY `subscriptions`.`fo_id`
ORDER BY MAX(`picture`.`since_id`) DESC
$limit
");
while ($sub_row = mysql_fetch_assoc($sub_query)) {
$subs [] = array(
'fo_id' => $sub_row['fo_id'],
'for_id' => $sub_row['for_id'],
'user_id' => $sub_row['user_id'],
'pic_id' => $sub_row['pic_id'],
'since' => $sub_row['since']
);
}
return $subs ;
}
My solution is to create another function to fetch the records from table removed_items and set a php condition where I call subscriptions_func() to skip/unset the records that resemble the records in subscriptions_func(), as the following
$sub = subscriptions_func($user_id);
foreach($sub as $sub){
$rmv_sub = rmv_items_func($sub[‘pic_id’]);
If($rmv_sub[‘pic_id’] != $sub[‘pic_id’]){
echo $sub[‘pic_id’];
}
}
This solution succeeded to skip the items in the table removed_items however this solution makes gaps in the array stored in the variable $sub which makes plank spots in the echoed items.
Is there a condition I can add to the function subscriptions_func() to cut all the additional conditions and checks?
Assuming id is the primary key of subscriptions and subs_id is the foreign key in removed_items, then you just have to add a condition to the WHERE clause. Something like this should work :
...
AND `subscriptions`.id NOT IN (SELECT `removed_items`.subs_id FROM `removed_items`)
...
Not related to your problem :
Your code seems vulnerable to SQL injection : use prepared statement to prevent this.
The original Mysql API is deprecated, it is highly recommended to switch to Mysqli instead.

Executing array values in a MySQL PDO statement with WHERE and OR

I've been trying to look for a solution where you can fetch database with one prepared statement and execute it with an array value
Typically I do this with my statement:
$search = $db->prepare("SELECT * FROM table WHERE name = ?");
$search->execute(array($name));
But what if i have an array like so:
Array (
[0] => Array
(
[name] => Burger Joint
)
[1] => Array
(
[name] => Burger Joint
)
[2] => Array
(
[name] => Burgers
)
[3] => Array
(
[name] => Meats
)
)
I'd like to somehow go through my database with either of the values in the array WHERE name=? in the statement. However, sometimes there's going to be multiple similar names, is there a way to condense the array before hand or what would be the best practice in a situation like this?
Thanks!
You can do this in a number of ways, but since you mentioned OR, let's use that:
First, your array of possible values. Let's take your array and mold it into an array of unique values:
$values_array = array_unique(
array_map(
function($element) {
return $element['name'];
},
$original_array
)
);
// $values_array now contains array('Burger Joint', 'Burgers', 'Meats')
Now, we build the prepared query by introducing as many placeholders as you have possible values:
$query = sprintf('SELECT * FROM table WHERE %s',
implode(
' OR ',
array_fill(
'name = ?',
count($values_array)
)
)
);
// $query now contains 'SELECT * FROM table WHERE name = ? OR name = ? OR name = ?'
and execute it:
$search = $db->prepare($query);
$search->execute($values_array);
Alternatively, you could use IN instead, building your query like so:
$query = sprintf('SELECT * FROM table WHERE name in (%s)',
implode(
', ',
array_fill(
'?',
count($values_array)
)
)
);
// $query now contains 'SELECT * FROM table WHERE name in (?, ?, ?)'
$search = $db->prepare($query);
$search->execute($values_array);
This will have the same effect, and it's slightly more clear what's going on by looking at the code.
Try name IN instead of name = .
First, you need IN. field IN (1,2) is equal to field=1 OR field=2.
Next, you need some sort of helper function, to put all that mess of technical details of creating correct SQL statements away from application business code. To make it in ONE line, not 50.
$data = $db->getAll("SELECT * FROM table WHERE name IN (?a)",$names);
Finally, it seems you're getting your names from another query.
In this case you have to run only single query using JOIN. You may ask another question under [mysql] tag providing both your queries.
To get only names into array you have to use another helper function (though you have to create it yourself or get somewhere first):
$names = $db->getCol("here goes your query to get names");

CakePHP has and belongs to many conditions with NOT EXISTS

$conditions = Array
(
[table] => products_pages
[alias] => ProductsPage
[type] => inner
[foreignKey] =>
[conditions] => Array
(
[0] => ProductsPage.product_id = Product.id
)
)
I'm trying to set up NOT EXISTS conditions, like the following SQL statement:
SELECT * FROM products_pages,products
WHERE NOT EXISTS (SELECT id
from products_pages
where products_pages.product_id = products.id)
So basically select any product that doesn't exist in the products_pages table.
What is the proper way to format that SQL statement for CakePHP and replace it here:
[conditions] => Array
(
[0] => (What's the proper way to insert above SQL here?
)
Would really appreciate your help guys, I've been trying to figure this out for about 5 hours with no luck. Thanks!
You can always use query if you don't find the way to do it with CakePHP:
http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#model-query
In this case security wouldn't be compromised as you are not using any input.
Anyway, something simple would be just to do it in more than one step:
//selecting the products in the productcs_pages table
$productsWithPages = /* query to get them*/
//getting an array of IDs
$productsWidthPagesIds = Hash::extract($productsWithPages, '{n}.Product.id');
//doing the NOT IN to select products without pages
$productsWithoutPages= $this->Product->find('all',
array('conditions' =>
array( 'NOT' => array('Product.id' => $productsWidthPagesIds )
)
);