How to save time.Now() in mysql table, column name as created_at timestamp null.
I am getting error :
Error:Error 1292: Incorrect datetime value: '2017-08-05 19:06:14.190 +0000' for column 'created_at' at row 1
More Information as asked :- ( I am using fragmenta cms, so all reference code with their line number is given below )
Table schema :-
mysql> describe users;
+----------------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| created_at | timestamp | YES | | NULL | |
| updated_at | timestamp | YES | | NULL | |
| status | int(11) | YES | | NULL | |
| role | int(11) | YES | | NULL | |
| name | varchar(250) | YES | | NULL | |
| email | varchar(250) | YES | | NULL | |
| title | varchar(250) | YES | | NULL | |
| summary | text | YES | | NULL | |
| text | text | YES | | NULL | |
| image_id | int(11) | YES | | NULL | |
| password_hash | varchar(250) | YES | | NULL | |
| password_reset_token | text | YES | | NULL | |
| password_reset_at | timestamp | YES | | NULL | |
+----------------------+--------------+------+-----+---------+----------------+
Code that is running it to save :-
At line no. 62 here ( https://github.com/fragmenta/fragmenta-cms/blob/master/src/pages/actions/setup.go#L62 )
It calls code
user := users.New()
in Line no. 51 at file here ( https://github.com/fragmenta/fragmenta-cms/blob/master/src/users/query.go#L51 )
New() function is setup.
Which is like :-
func New() *User {
user := &User{}
user.CreatedAt = time.Now()
user.UpdatedAt = time.Now()
user.TableName = TableName
user.KeyName = KeyName
user.Status = status.Draft
return user
}
and their connecting / mysql opening pattern is located here ( https://github.com/fragmenta/query/blob/master/adapters/database_mysql.go#L23 ) .
There is a bug in https://github.com/fragmenta/query. The TimeString method in query/adapters/database.go is not valid for all DBMS adapters.
// TimeString - given a time, return the standard string representation
func (db *Adapter) TimeString(t time.Time) string {
return t.Format("2006-01-02 15:04:05.000 -0700")
}
It's not valid for a MySQL timestamp: MySQL 5.7 Reference Manual, 11.3.1 The DATE, DATETIME, and TIMESTAMP Types. The MySQL TimeString method in query/adapters/database_mysql.go should be:
// TimeString - given a time, return the MySQL standard string representation
func (db *MysqlAdapter) TimeString(t time.Time) string {
return t.Format("2006-01-02 15:04:05.999999")
}
You are trying to insert it using a string query.go:36:
now := query.TimeString(time.Now().UTC())
that is generated by the package that you are using database.go:59:
return t.Format("2006-01-02 15:04:05.000 -0700")
MySQL expects it to be in the pattern of yyyy-MM-dd hh:mm:ss, use the following snippet to apply the pattern to you current Time.time object:
now := time.Now().UTC().Format("2006-01-02 03:04:05")
Anyway, why not to use the SQL function NOW() when inserting the record ?
Related
I have three tables topics, category(HowtoCategory::class), sections(Howto::class).
Multiple categories belong to one topic and multiple sections belong to one category.
Topic Has Many Category
Category Has Many Sections
Category Belongs to Topic
Sections Belongs To Category
Topic Has Many Sections Through Category
I want to search through the sections(Howto::class) but display the related topics. How can I access topics in the controller from my query search of sections? I dont want to access it in the view but in the controller.
Controller
public function index(Request $request)
{
if (request()->filled('search')) {
request()->fullUrlWithQuery(['search ' => null]);
$sections = Howto::search($request->search)->get();
$request = $request->input('search');
} else {
$sections = null;
}
return view('howto-pages.howto-main', [
'sections' => $sections,
]);
}
Models
class Topic extends Model
{
public function categories()
{
return $this->hasMany(HowtoCategory::class);
}
public function sections()
{
return $this->hasManyThrough(Howto::class, HowtoCategory::class);
}
}
class HowtoCategory extends Model
{
public function sections()
{
return $this->hasMany(Howto::class);
}
public function topic()
{
return $this->belongsTo(Topic::class);
}
}
class Howto extends Model
{
public function category()
{
return $this->belongsTo(HowtoCategory::class);
}
}
Tables
mysql> desc howto;
+-------------------+-----------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------------+-----------------+------+-----+---------+----------------+
| id | bigint unsigned | NO | PRI | NULL | auto_increment |
| title | varchar(255) | NO | | NULL | |
| body | mediumtext | YES | | NULL | |
| description | mediumtext | YES | | NULL | |
| created_at | timestamp | YES | | NULL | |
| updated_at | timestamp | YES | | NULL | |
| section_id | int | YES | | NULL | |
| howto_category_id | bigint unsigned | YES | MUL | NULL | |
+-------------------+-----------------+------+-----+---------+----------------+
mysql> desc howto_category;
+----------------------+-----------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------------------+-----------------+------+-----+---------+----------------+
| id | bigint unsigned | NO | PRI | NULL | auto_increment |
| howto_category_title | varchar(255) | NO | | NULL | |
| icon | varchar(255) | YES | | NULL | |
| description | mediumtext | YES | | NULL | |
| intro | text | YES | | NULL | |
| category_id | int | YES | | NULL | |
| created_at | timestamp | YES | | NULL | |
| updated_at | timestamp | YES | | NULL | |
| topic_id | bigint unsigned | YES | MUL | NULL | |
+----------------------+-----------------+------+-----+---------+----------------+
mysql> desc topics;
+-------------+-----------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+-----------------+------+-----+---------+----------------+
| id | bigint unsigned | NO | PRI | NULL | auto_increment |
| topic_title | varchar(255) | NO | | NULL | |
| description | mediumtext | YES | | NULL | |
| created_at | timestamp | YES | | NULL | |
| updated_at | timestamp | YES | | NULL | |
+-------------+-----------------+------+-----+---------+----------------+
First and foremost i'd define the foreignIDS in the relations just to make sure that are working as expected.
class Topic extends Model
{
public function categories()
{
return $this->hasMany(HowtoCategory::class);
}
public function sections()
{
return $this->hasManyThrough(
Howto::class, HowtoCategory::class,
"topic_id", "howto_category_id"
);
}
}
then you can get the Topics by searching the sections like so
use Illuminate\Database\Eloquent\Builder;
$topics = Topic::whereHas("sections", function(Builder $query) {
$query->where("howto.description", "something to search")
})->get();
I am a newcomer to Go. I have an old tool to check and compare data in the Mysql database to my device, and I want to rewrite the tool in Go.
Since the tables and data have been already in the Mysql, I try to use GORM to auto map the existing tables. But I am not sure how to do that? I did not find any description of automapping an existing table in the GORM documentation.
I redeclare the existing table model and try to query data. The procedure is as below:
For example one of my tables is like this:
MariaDB [neutron]> desc lbaas_loadbalancers;
+---------------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------------------+--------------+------+-----+---------+-------+
| project_id | varchar(255) | YES | MUL | NULL | |
| id | varchar(36) | NO | PRI | NULL | |
| name | varchar(255) | YES | | NULL | |
| description | varchar(255) | YES | | NULL | |
| vip_port_id | varchar(36) | YES | MUL | NULL | |
| vip_subnet_id | varchar(36) | NO | | NULL | |
| vip_address | varchar(36) | YES | | NULL | |
| admin_state_up | tinyint(1) | NO | | NULL | |
| provisioning_status | varchar(16) | NO | | NULL | |
| operating_status | varchar(16) | NO | | NULL | |
| flavor_id | varchar(36) | YES | MUL | NULL | |
+---------------------+--------------+------+-----+---------+-------+
11 rows in set (0.002 sec)
MariaDB [neutron]> select * from lbaas_loadbalancers \G;
*************************** 1. row ***************************
project_id: 346052548d924ee095b3c2a4f05244ac
id: f6638d02-29f8-41aa-9433-179bf49f5fbd
name: test1
description:
vip_port_id: 21cebbd5-fa4c-4d20-9858-d14ba3eacea8
vip_subnet_id: 0916f471-afcd-48ee-afc5-56bcb0efa963
vip_address: 172.168.1.6
admin_state_up: 1
provisioning_status: ACTIVE
operating_status: ONLINE
flavor_id: NULL
1 row in set (0.003 sec)
Then I try to use GORM mapping the table. I just chosen two fields ID and Name for the test.
package main
import (
"log"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
// declare only two attribute in the model for test purpose
type Lbaas_loadbalancers struct {
ID string
Name string
}
func main() {
var lb Lbaas_loadbalancers
dsn := "test:test#tcp(192.168.0.17:3306)/test?charset=utf8mb4&parseTime=True&loc=Local"
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
log.Fatal("connection error")
}
test := db.Take(&lb)
log.Println("test err is ", test.Error)
log.Println(test.RowsAffected)
// this line report error: ./db.go:25:6: test.ID undefined (type *gorm.DB has no field or method ID)
log.Println(test.ID)
// if I comment the above line, this print out 'mysql', but the actual name is 'test1'.
log.Println(test.Name())
}
Finally, I run go run db.go, I got this error:
➜ test git:(main) ✗ go run db.go
# command-line-arguments
./db.go:27:20: cannot convert test.Config.Dialector.Name (type func() string) to type string
It seems not the right way to do it. what is the correct way to auto map an existing database in Mysql by using GORM module?
If the below code is the correct way, why I cannot get the ID attribute from the return value of db.Take method directly? Do I need to do data conversion?
Please give me some hints, thanks.
I know what is wrong here, I should not get ID and Name from the db.Take return, It takes the address of lb variable, and change the lb.
I am so silly, just realized the problem. :)
I have a table on my DB with these columnns:
+-----------------+---------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------------+---------------------+------+-----+---------+----------------+
| id | bigint(20) unsigned | NO | PRI | NULL | auto_increment |
| name | varchar(255) | NO | | NULL | |
| value | varchar(255) | NO | | NULL | |
+-----------------+---------------------+------+-----+---------+----------------+
I would access to value values by name.
For example I have these datas:
+----+------------+------------+
| id | name | value |
+----+------------+------------+
| 1 | start_date | 2020-01-01 |
| 2 | end_date | 2021-01-01 |
+----+------------+------------+
I would to get '2020-01-01' by 'start_date'.
I tried this code, but I'm not satisfyed because with this code I get all values of the row, not only the value expected.
Configuration::get()->keyBy('start_date');
I'm not sure I was clear.
Let me know.
Thanks a lot!!
Assuming you want to get an array of key/value pairs, and each key in the name column is unique, you can simply use pluck() (https://laravel.com/docs/8.x/collections#method-pluck):
$configuration = Configuration::pluck('value', 'name');
dd($configuration);
// ['start_date' => '2020-01-01', 'end_date' => '2021-01-01']
Then, you'd use simply array access to use these configuration settings where applicable:
$startDate = $configuration['start_date']; // '2020-01-01'
$endDate = $configuration['end_date']; // '2021-01-01'
...
I am following a tutorial for strapi and am stuck at a part where I query for dishes belonging to a restaurant. I'm sure everything is set up properly with a one(restaurant) to many(dishes) relationship defined but the query doesn't work. I've traced it to the actual query which is:
query {
restaurant(id: "1") {
id
name
dishes {
name
description
}
}
}
which returns an error when I run it in playground. The query doesn't show any issues while I write it and doesn't allow me to write anything like:
query {
restaurant(where:{id: "1"}) {
id
name
dishes {
name
description
}
}
}
My database is mysql and the two tables look like this:
mysql> describe dishes;
+-------------+---------------+------+-----+-------------------+-----------------------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+---------------+------+-----+-------------------+-----------------------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(255) | YES | MUL | NULL | |
| description | longtext | YES | | NULL | |
| price | decimal(10,2) | YES | | NULL | |
| restaurant | int(11) | YES | | NULL | |
| created_at | timestamp | NO | | CURRENT_TIMESTAMP | |
| updated_at | timestamp | NO | | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |
+-------------+---------------+------+-----+-------------------+-----------------------------+
7 rows in set (0.00 sec)
mysql> describe restaurants;
+-------------+--------------+------+-----+-------------------+-----------------------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+--------------+------+-----+-------------------+-----------------------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(255) | YES | MUL | NULL | |
| description | longtext | YES | | NULL | |
| created_at | timestamp | NO | | CURRENT_TIMESTAMP | |
| updated_at | timestamp | NO | | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |
+-------------+--------------+------+-----+-------------------+-----------------------------+
5 rows in set (0.00 sec)
These tables where auto generated by strapi.
The full error in playground is this:
{
"errors": [
{
"message": "Undefined binding(s) detected when compiling SELECT query: select `restaurants`.* from `restaurants` where `restaurants`.`id` = ? limit ?",
"locations": [
{
"line": 2,
"column": 3
}
],
"path": [
"restaurant"
],
"extensions": {
"code": "INTERNAL_SERVER_ERROR",
"exception": {
"stacktrace": [
"Error: Undefined binding(s) detected when compiling SELECT query: select `restaurants`.* from `restaurants` where `restaurants`.`id` = ? limit ?",
" at QueryCompiler_MySQL.toSQL (/Users/redqueen/development/deliveroo/server/node_modules/knex/lib/query/compiler.js:85:13)",
" at Builder.toSQL (/Users/redqueen/development/deliveroo/server/node_modules/knex/lib/query/builder.js:72:44)",
" at /Users/redqueen/development/deliveroo/server/node_modules/knex/lib/runner.js:37:34",
"From previous event:",
" at Runner.run (/Users/redqueen/development/deliveroo/server/node_modules/knex/lib/runner.js:33:30)",
" at Builder.Target.then (/Users/redqueen/development/deliveroo/server/node_modules/knex/lib/interface.js:23:43)",
" at runCallback (timers.js:705:18)",
" at tryOnImmediate (timers.js:676:5)",
" at processImmediate (timers.js:658:5)",
" at process.topLevelDomainCallback (domain.js:120:23)"
]
}
}
}
],
"data":
Any idea why this is happening?
It seems this was a bug with the alpha.v20 and alpha.v21 versions of strapi. A bug fix has been published to solve it, an issue thread on github is here.
I have three tables:
- Venue
- Space (belongs to Venue)
- Included Space (belongs to Space)
I receive the id of a Venue in the route and return all the related spaces that I know have Included Spaces(a field called num_included_spaces__c on the Space record that maintains a count of its children). Now that I have all the related parent Spaces for that Venue, I need to find all of the Included Spaces for them.
An Included Space is still a Space, it just happens to have a parent that resides in the same table. I'm trying to turn this:
Venue = Rockdog
- Space = Upstairs
- Space = Media Room
- Space = Courtyard
- Space = Downstairs
- Space = Front Patio
- Space = Indoor Bar
Into this:
Venue = Rockdog
- Space = Upstairs
-- Included Space = Media Room
-- Included Space = Courtyard
- Space = Downstairs
-- Included Space = Front Patio
-- Included Space = Indoor Bar
The Included Spaces table has belongs_to__c and space__c as fields, where belongs_to__c is the id of the parent space and space__c is the id of the child. So i'm looking to find all the Included Spaces where belongs_to_c matches the id of any #spaces returned below
#sub_spaces = Space.where("venue__c = ? AND num_included_spaces__c = ?", params[:venue],0)
#spaces = Space.where("venue__c = ? AND num_included_spaces__c > ?", params[:venue],0)
How would I write this Active Record Query for #included_spaces?
my database schema.
mysql> describe venues;
+------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(255) | YES | | NULL | |
| created_at | datetime | NO | | NULL | |
| updated_at | datetime | NO | | NULL | |
+------------+--------------+------+-----+---------+----------------+
4 rows in set (0,00 sec)
mysql> describe spaces;;
+------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(255) | YES | | NULL | |
| venue_id | int(11) | YES | | NULL | |
| created_at | datetime | NO | | NULL | |
| updated_at | datetime | NO | | NULL | |
+------------+--------------+------+-----+---------+----------------+
5 rows in set (0,00 sec)
ERROR:
No query specified
mysql> describe included_spaces;;
+------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(255) | YES | | NULL | |
| space_id | int(11) | YES | | NULL | |
| created_at | datetime | NO | | NULL | |
| updated_at | datetime | NO | | NULL | |
+------------+--------------+------+-----+---------+----------------+
5 rows in set (0,00 sec)
ERROR:
No query specified
Below function will somehow give you the result you need (in console ofcourse ) however it's not a good solution - it queries database more than needed. However it is the easy -))
def foo id
v = Venue.find(id)
puts v.name
v.spaces.each do |space|
puts space.name
space.included_spaces.each do |spis|
puts spis.name
end
end
end
You can also try a more complex query sth like,
mysql> SELECT spaces.name, included_spaces.name FROM `spaces` INNER JOIN `venues` ON `venues`.`id` = `spaces`.`venue_id` INNER JOIN `included_spaces` ON `included_spaces`.`space_id` = `spaces`.`id` WHERE `spaces`.`venue_id` = 1
-> ;
+------------+-----------+
| name | name |
+------------+-----------+
| Upstairs, | Front |
| Upstairs, | Patio, |
| Upstairs, | Indoor |
| Upstairs, | Bar |
| Downstairs | Media |
| Downstairs | Room, |
| Downstairs | Courtyard |
+------------+-----------+
7 rows in set (0,00 sec)
which should be translated to active record as
Space.joins(:venue)
.joins(:included_spaces)
.where(venue_id: 1)
.select('spaces.name, included_spaces.name')