I'm trying to delete records in Yii2 using folowing code:
$query = "DELETE `master_contacts`
FROM `master_contacts`
LEFT JOIN `master_list_contacts`
ON `master_list_contacts`.`master_contact_id` = `master_contacts`.`id`
WHERE `master_contacts`.`deleted` = 1
AND `master_list_contacts`.`id` IS NULL";
Yii::$app->db->createCommand($query);
I have Following database structure.
Query works perfectly in mysql client but I can't get it work in yii (although I didn't get any error).
Could someone tell me please how I supposed do this in yii?
If you use pure SQL you should call execute method:
$query = "DELETE `master_contacts`
FROM `master_contacts`
LEFT JOIN `master_list_contacts`
ON `master_list_contacts`.`master_contact_id` = `master_contacts`.`id`
WHERE `master_contacts`.`deleted` = 1
AND `master_list_contacts`.`id` IS NULL";
Yii::$app->db->createCommand($query)->execute();
Related
i tried to do this insert and update another table with the sum of the data and the new values, but im getting wrong results
please help me convert this laravel to sql.
thanks in advance:
laravel:
$viaturas = Viaturas::firstWhere('matricula', $viaverde->matricula);
$viaturas->total_viaverde = $viaverde->custo + $viaturas->total_viaverde;
$viaturas->update();
sql not doing right as follows:
UPDATE `viaturas`
INNER JOIN `viaverde` ON `viaverde`.`matricula`=`viaturas`.`matricula`
SET `viaturas`.`total_viaverde` = (SELECT SUM(`viaverde`.`custo`));
The correct method is save()
$viaturas = Viaturas::firstWhere('matricula', $viaverde->matricula);
$viaturas->total_viaverde = $viaverde->custo + $viaturas->total_viaverde;
$viaturas->save();
If you use update(), you have two options
From the Model object
$viaturas = Viaturas::firstWhere('matricula', $viaverde->matricula);
# update this $viatura model
$viaturas->update(['total_viaverde' => $viaverde->custo + $viaturas->total_viaverde]);
From the Query Builder
# update every Viatura where matricula = $viaverde->matricula
Viaturas::query()
->where('matricula', $viaverde->matricula)
->update(['total_viaverde' => $viaverde->custo + $viaturas->total_viaverde]);
To run that specific SQL query from the query builder, I think this should do it
Viatura::query()
->join('viaverde', 'viaverde.matricula', 'viaturas.matricula')
->update(['viaturas.total_viaverde' => DB::raw('select sum(`viaverde`.`custo`)')]);
I need to
1. run a select query on MYSQL DB and fetch the records.
2. Records are processed by python script.
I am unsure about the way I should proceed. Is xcom the way to go here? Also, MYSQLOperator only executes the query, doesn't fetch the records. Is there any inbuilt transfer operator I can use? How can I use a MYSQL hook here?
you may want to use a PythonOperator that uses the hook to get the data,
apply transformation and ship the (now scored) rows back some other place.
Can someone explain how to proceed regarding the same.
Refer - http://markmail.org/message/x6nfeo6zhjfeakfe
def do_work():
mysqlserver = MySqlHook(connection_id)
sql = "SELECT * from table where col > 100 "
row_count = mysqlserver.get_records(sql, schema='testdb')
print row_count[0][0]
callMYSQLHook = PythonOperator(
task_id='fetch_from_testdb',
python_callable=mysqlHook,
dag=dag
)
Is this the correct way to proceed?
Also how do we use xcoms to store the records for the following MySqlOperator?'
t = MySqlOperator(
conn_id='mysql_default',
task_id='basic_mysql',
sql="SELECT count(*) from table1 where id > 10",
dag=dag)
I was really struggling with this for the past 90 minutes, here is a more declarative way to follow for newcomers:
from airflow.hooks.mysql_hook import MySqlHook
def fetch_records():
request = "SELECT * FROM your_table"
mysql_hook = MySqlHook(mysql_conn_id = 'the_connection_name_sourced_from_the_ui', schema = 'specific_db')
connection = mysql_hook.get_conn()
cursor = connection.cursor()
cursor.execute(request)
sources = cursor.fetchall()
print(sources)
...your DAG() as dag: code
task = PythonOperator(
task_id = 'fetch_records',
python_callable = fetch_records
)
This returns to the logs the contents of your DB query.
I hope this is of use to someone else.
Sure, just create a hook or operator and call the get_records() method: https://airflow.apache.org/docs/apache-airflow/stable/_modules/airflow/hooks/dbapi.html
How to call a view mysql from phalcon
I'm doing this in my phalcon controller:
$phql = "select id,description,name,dni from ViewUser where name like '%mark%' ";
$usuario = $this->modelsManager->executeQuery($phql);
Apparently I'm getting an error processing the where, why if yo process this:
$phql = "select id,description,name,dni from ViewUser";
$usuario = $this->modelsManager->executeQuery($phql);
I no longer get error.
For the call of the view, already create my model ViewUser.
I do not know what is wrong when I put the conditions in the WHERE.
Any help is welcome. Thank.
I have a MYSQL table called 'devices'. I've successfully done the bin/cake bake all. In fact I have the auto-built DevicesController.php fully working. But I can't figure out how to count the rows in a table. I've tried:
$conn = ConnectionManager::get('default');
$numRows = $conn->execute('select count(*) from devices');
and
$this->DeviceSetups = TableRegistry::get('Devices');
$numRows = $this->Devices->query('select count(*) from devices'); // both like this
$numRows = $this->Devices->query('select count(*) from devices')->execute(); // and like this
and
$this->DeviceSetups = TableRegistry::get('Devices');
$numRows = $this->Devices->find('count');
Going thru mysql_query() isn't really a good idea because I have all the access info already setup in app.php for CakePHP to use. I tried something else using AnyModel that didn't work.
The former 2 attempts return a Cake\Database\Statement\MysqlStatement not an integer with the number of rows in the table. I've consulted this answer and this answer and read the CakePHP docs. Nothing seems to tell me how to count up a table nor how to execute a raw My SQL command string and then access the result.
TableRegistry::get('DeviceSetups')->find()->count();
See http://book.cakephp.org/3.0/en/orm/retrieving-data-and-resultsets.html#getting-a-count-of-results.
If you want to count in table then it should be like below.
$count = $this->find()->count();
echo $count;
Is there any possible way to convert the MySQL object into criteria object? I tried this query:
select
p.disrepid,
p.subject, p.body,
c.disrepid as disrepid1,
c.subject as subject1,
c.body as body1
from discusreply as p, discusreply as c
where p.distopid=' . $this->id . '
and (c.disrepid = p.parentid or c.parentid = p.distopid)
order by p.disrepid ASC
I tried a lot for converting this query into a Criteria, But nothing happened. I want this criteria object for passing this into Pager class for completing the pagination.
$pager->setCriteria($c);.
You can use your own SQL do perform a query, but there is no automated way to turn sql into a Criteria object.
$con = Propel::getConnection(DATABASE_NAME);
$sql = "SELECT books.* FROM books
WHERE NOT EXISTS (SELECT id FROM review WHERE book_id = book.id)";
$stmt = $con->createStatement();
$rs = $stmt->executeQuery($sql, ResultSet::FETCHMODE_NUM);
$books = BookPeer::populateObjects($rs);
This bypasses Criterion objects all together. You mentioned wanting a criteria object so you could feed this into a pager. You can instead set a custom select method into your pager, which will then perform your custom query. If you need to pass a parameter into this, I would recommend extending sfPropel with your own pager class that can optionally pass parameters to your peer select methods so you don't have to use Criteria objects at all. As a quick alternative, you can do something like this, using your Criteria as a container for your select parameters:
$c = new Criteria();
$c->add(DiscussreplyPeer::ID, $myId);
$pager = new sfPropelPager();
$pager->setCriteria($c);
$pager->setPeerMethod('getReplies');
And then in your peer class:
public static function getReplies(Criteria $c) {
$map = $c->getMap();
$replyId = $map[DiscussreplyPeer::ID]->getValue();
$con = Propel::getConnection(DATABASE_NAME);
$sql = "select p.disrepid, p.subject, p.body, c.disrepid as disrepid1, c.subject as subject1, c.body as body1 from discusreply as p, discusreply as c where p.distopid=? and (c.disrepid = p.parentid or c.parentid = p.distopid) order by p.disrepid ASC";
$stmt = $con->prepareStatement($sql);
$stmt->setString(1, $replyId);
$rs = $stmt->executeQuery();
$results = array();
while ($rs->next()) {
// for example
$results['disrepid'] = $rs->getInt('disrepid');
}
return $results;
}
More tips on propel and symfony can be found at:
http://stereointeractive.com/blog/2007/06/12/propel-queries-using-custom-sql-peer-classes-and-criterion-objects/
This site will help a lot for learning to write criteria - you can use it to generate criteria code from pseudo SQL. I would also recommend grabbing the Symfony/Propel cheat sheets.
For your query in particular you will want something like this:
$c = new Criteria();
$c->addJoin(discusreply::DISREPID, discusreply::PARENTID, Criteria::INNER_JOIN);
$c->clearSelectColumns();
$c->addSelectColumn(discusreplyPeer::Disrepid);
...
$c->add(discusreplyPeer::DISTOPID, $this->id, Criteria::EQUAL);
...
$c->addAscendingOrderByColumn(discusreply::DISREPID);
I'm not sure that the Criteria system supports multiple clauses for an inner join so you may have to revert back to ad-hoc SQL for this query (if it does I would love to know how). The following code will create a ResultSet object similar to what you would get from simple database abstraction layers.
$sql = "SELECT ...";
$dbh = Propel::getConnection([DB]);
$sth = $dbh->createStatement();
$res = $sth->executeQuery($sql, ResultSet::FETCHMODE_NUM);
I don't think there is much of a disadvantage to using the ad-hoc method on a query like this since you will have to deal with ResultSet objects rather than table-specific objects when you are returning only specific columns.
You can try auto-generating the criteria from sql using this site.