Log the actual SQL query using ActiveRecord with Yii2?

Method 1 With relations that return yii\db\ActiveQuery instance it’s possible to extract the raw SQL query directly in code for example with var_dump(). For example if we have user relation: /** * @return \yii\db\ActiveQuery */ public function getUser() { return $this->hasOne(User::className(), [‘id’ => ‘user_id’]); } You can then var_dump() the raw SQL like that: var_dump($model->getUser()->prepare(Yii::$app->db->queryBuilder)->createCommand()->rawSql); … Read more

has_and_belongs_to_many, avoiding dupes in the join table

Prevent duplicates in the view only (Lazy solution) The following does not prevent writing duplicate relationships to the database, it only ensures find methods ignore duplicates. In Rails 5: has_and_belongs_to_many :tags, -> { distinct } Note: Relation#uniq was depreciated in Rails 5 (commit) In Rails 4 has_and_belongs_to_many :tags, -> { uniq } Prevent duplicate data … Read more

Is there a way to avoid automatically updating Rails timestamp fields?

Do this in a migration or in a rake task (or in the new database seeds if you’re on edge rails): ActiveRecord::Base.record_timestamps = false begin run_the_code_that_imports_the_data ensure ActiveRecord::Base.record_timestamps = true # don’t forget to enable it again! end You can safely set created_at and updated_at manually, Rails won’t complain. Note: This also works on individual … Read more

How to list of all the tables defined for the database when using active record?

Call ActiveRecord::ConnectionAdapters::SchemaStatements#tables. This method is undocumented in the MySQL adapter, but is documented in the PostgreSQL adapter. SQLite/SQLite3 also has the method implemented, but undocumented. >> ActiveRecord::Base.connection.tables => [“accounts”, “assets”, …] See activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb:21, as well as the implementations here: activerecord/lib/active_record/connection_adapters/mysql_adapter.rb:412 activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb:615 activerecord/lib/active_record/connection_adapters/sqlite_adapter.rb:176

PGError: ERROR: aggregates not allowed in WHERE clause on a AR query of an object and its has_many objects

The error message tells you: aggregates not allowed in WHERE clause count() is an aggregate function. Use the HAVING clause for that. The query could look like this: SELECT r.* FROM recommendations r JOIN approvals a ON a.recommendation_id = r.id WHERE r.user_id = $current_user_id GROUP BY r.id HAVING count(a.recommendation_id) = 1 With PostgreSQL 9.1 or … Read more