24hoursmedia-craftcms / views-work

Craft CMS views plugin
Other
1 stars 2 forks source link

Best way to "import" stats #106

Closed davorpeic closed 1 year ago

davorpeic commented 1 year ago

Hi, I'm migrating a site that already have some number of entry views in a custom text field. What would be the best way to pass it to your plugin?

thanks dp

24hoursmedia-craftcms commented 1 year ago

Hi, there is not directly an 'easy' way, there is no migration script included in the plugin for this.

Personally, I would do it like this:

Write a database query or migration script, that updates or creates records directly in the views work table. The table to update looks like this, so it should be easy.

image

You can get the element id, site id, and probably the existing view counter prefixed with 'field_' in the craft_content table which looks like this:

image

Let me know if this works for you, I might be able to expose some functionality in twig to directly set the views on an entry, which might be more easy to implement for smaller sites.

But I prefer not to since it mixes up template logic with domain logic.

davorpeic commented 1 year ago

Hey,

yeah, this was my backup approach even I didn't expected this feature to be available, just wanted some kind of confirmation :)

So in my case I just have "views total" basically, so I should just update that column and leave other ones to 0 or not sure what is the default state of the column.

dp

24hoursmedia-craftcms commented 1 year ago

Yes, also craft also needs an uid. You can write a mysql function to generate one, or maybe use the id of the craft_content (I think it will not be mixed up, views work does not need the uid anyways but YII requires it).

First you'd need to create a views work entry for each content entry and migrate the total value from your content table.

INSERT IGNORE INTO craft_viewswork_viewrecording (dateCreated, dateUpdated, uid, siteId, elementId, viewsTotal, viewsToday, viewsThisWeek, viewsThisMonth) 
SELECT NOW(),NOW(),uid,siteId,elementId,/* REPLACE THIS 0 WITH THE FIELDNAME IN YOUR CRAFT_CONTENT:*/0,0,0,0 FROM craft_content

Then if your site is already in production, and viewsWork entries have already been created, you can create an additional update statement to update the viewsTotal with values that already exist, or perhaps even add the values:

UPDATE `craft_viewswork_viewrecording` r INNER JOIN craft_content c ON (r.siteId=c.siteId and r.elementId = c.elementId) SET r.viewsTotal = r.viewsTotal + /* Replace with the fieldName: c.FIELDNAME */ 0

After you tested in dev you could write a migration. Hope this helps!

davorpeic commented 10 months ago

Hi, just a followup, the first insert works great!

Thanks!

Davor

24HOURSMEDIA commented 10 months ago

Great to hear it worked smoothly!