Laravel Shared hosting ajax delete - ajax

I hosted my site on freehosting for testing purposes, and everything works perfectly but Ajax delete. When I click on delete, delete function goes through and everything is deleted, but for some reason it returns 500 error. Locally it works without a problem.
Route::delete('/admin/deleteRound', 'AdminCyclesController#deleteRound')->name('admin.deleteRound');
and
$.ajax({
type: "POST",
url: urlDeleteRound,
data: {cycle_id: cycle_id, round: round, _token: token, _method: 'delete'}
}).success(function (response) {.....});
I tried everything I could find online but without success. Is there a way to fix this, or at least a way to figure out where the problem lies?
EDITED - .log
I don't know what to make out of this.
local.ERROR: SQLSTATE[HY000]: General error (SQL: DELETE FROM cycle_team where cycle_team.cycle_id=9 and cycle_team.round=1) {"userId":1,"email":"xxxxxx#gmail.com","exception":"[object] (Illuminate\Database\QueryException(code: HY000): SQLSTATE[HY000]: General error (SQL: DELETE FROM cycle_team where cycle_team.cycle_id=9 and cycle_team.round=1) at /storage/ssd5/708/6079708/laravel/vendor/laravel/framework/src/Illuminate/Database/Connection.php:664, PDOException(code: HY000): SQLSTATE[HY000]: General error at /storage/ssd5/708/6079708/laravel/vendor/laravel/framework/src/Illuminate/Database/Connection.php:332)
Edit 2 - Code perfoming deletion
public function deleteRound(Request $request){
$round=$request['round'];
$id=$request['cycle_id'];
DB::select("DELETE FROM `cycle_team` where cycle_team.cycle_id=$id and cycle_team.round=$round");
$teams = DB::select("SELECT teams.id, teams.title,sum(ct.points) + sum(ct.is_winner) + sum(ct.is_over) as points, sum(ct.points) + sum(ct.is_winner) + sum(ct.is_over)-Min(ct.points + ct.is_winner + ct.is_over) as minpoints, COUNT(teams.id)-1 as number FROM `teams`INNER JOIN cycle_team as ct on teams.id =ct.team_id INNER JOIN cycles as c on c.id = ct.cycle_id where ct.cycle_id =$id > 0 GROUP BY ct.cycle_id, ct.team_id, teams.title, teams.id order by points desc");
return response()->json(['teams'=>$teams]);
}
SOLUTION
DB::select("DELETE FROM `cycle_team` where cycle_team.cycle_id=$id and cycle_team.round=$round")
was making problems, using Builder solves the problem
DB::table('cycle_team')->where('cycle_id', id)->where('round', $round)->delete();

You're using DB::select() which, under the hood, uses a read-only PDO instance by default. As DELETE is a write operation, the general error is occurring.
Consider using the DB::delete() method instead of DB::select(), since that's the type of operation you're performing.
You could also use DB::statement(), which returns a boolean based on the success of the query, or DB::affectingStatement() if you'd like the number of rows affected by the query.
Or, as suggested in the comments, use the Query Builder to build a delete query.
DB::table('cycle_team')
->where('cycle_id', $id)
->where('round', $round)
->delete();

Related

Web.Content calling API service and merging pages with List.Transform started to fail

I created PowerBI report which which is connecting to data source via API service. Returning json contains thousands of entities. API service is called via Web.Content function. API service returns always total record count and so we are able to calculate nr. of pages which has to be called to obtain whole dataset. This report is displaying data from our servicedesk app, which is deployed on many servers and for many customers and use Query parameters to connect to any of these servers.
Detail of Power query is below.
Why am I writing here. This report was working without any issue more than 1,5 year but on August 17th one of servers start causing erros in step Pages where are some random lines (pages) with errors - see attached picture labeled "Errors in step Pages". and this is reason that next step Entities (List.Union) in query is stopping refresh and generate errors with message:
Expression.Error: We cannot apply field access to the type List. Details: Value=[List] Key=requests
What is notable
API service si returning records in the same order but faulty lists are random when calling with same parameters
some times is refresh without any error
The same power query called on another server is working correctly , problem is only with one specific server.
This problem started without notice on the most important server after 1,5 year without any problem.
Here is full text power of query for this main source, which is used later in other queries to extract all necessary data. Json is really complicated and I extract from it list of requests, list of solvers, list of solver groups,.... and this base query and its output is input for many referenced queries.
Errors in step Pages
let
BaseAPIUrl = apiurl&"apiservice?", /*apiurl is parameter - name of server e.g. https://xxxx.xxxxxx.sk/ */
EntitiesPerPage = RecordsPerPage, /*RecordsPerPage is parameter and defines nr. of record per page - we used as optimum 200-400 record per pages, but is working also with 4000 record per page*/
ApiToken = FnApiToken(), /*this function is returning apitoken value which is returning value of another api service apiurl&"api/auth/login", which use username and password in body of call to get apitoken */
GetJson = (QParm) => /*definiton general function to get data from data source*/
let
Options =
[ Query= QParm,
Headers=
[
Accept="application/json",
ApiKeyName="apitoken",
Authorization=ApiToken
]
],
RawData = Web.Contents(BaseAPIUrl, Options),
Json = Json.Document(RawData)
in Json,
GetEntityCount = () => /*one times called function to get nr of records using GetJson, which is returned as a part of each call*/
let
QParm = [pp="1", pg="1" ],
Json = GetJson(QParm),
Count = Json[totalRecord]
in
Count,
GetPage = (Index) => /*repeatadly called function to get each page of json using GetJson*/
let
PageNr = Text.From(Index+1),
PerPage = Text.From(EntitiesPerPage),
QParm = [pg = PageNr, pp=PerPage],
Json = GetJson(QParm),
Value = Json[data][requests]
in Value,
EntityCount = List.Max({ EntitiesPerPage, GetEntityCount() }), /*setup of nr. of records to variable*/
PageCount = Number.RoundUp(EntityCount / EntitiesPerPage), /*setup of nr. of pages */
PageIndices = { 0 .. PageCount - 1 },
Pages = List.Transform(PageIndices, each GetPage(_) /*Function.InvokeAfter(()=>GetPage(_),#duration(0,0,0,1))*/), /*here we call for each page GetJson function to get whole dataset - there is in comment test with delay between getpages but was not neccessary*/
Entities = List.Union(Pages),
Table = Table.FromList(Entities, Splitter.SplitByNothing(), null, null, ExtraValues.Error)
I also tried another way of appending pages to list using List.Generate. This is also bringing random errors in list but
it is bringing possibility to transform to table in contrast with original way with using List.Transform, but other referenced queries are failing and contains on the last row errors
When I am exploring content of faulty page/list extracting it via Add as New Query there are always all record without any fail.....
Source = List.Generate( /*another way to generate list of all pages*/
() => [Page = 0, ReqPageData = GetPage(0) ],
each [Page] < PageCount,
each [ReqPageData = GetPage( [Page] ),
Page = [Page] + 1 ],
each [ReqPageData]
),
#"Converted to Table" = Table.FromList(Source, Splitter.SplitByNothing(), null, null, ExtraValues.Error), /*here i am able to generate table from list in contrast when is used List.Generate*/
#"Expanded Column1" = Table.ExpandListColumn(#"Converted to Table", "Column1"), /*here aj can expand list to column*/
#"Removed Errors" = Table.RemoveRowsWithErrors(#"Expanded Column1", {"Column1"}) /*here i try to exclude errors, but i dont know what happend and which records (if any) are excluded*/
Extracting errored page
and finnaly I am tottaly clueless not able to find the cause of this behavior on this specific server. I tested to call pages which are errored via POSTMAN, I discused this issue with author of API service and He also tried to call this API service with all parameters but server is returning every page OK, only Power query is not able to List.Transform ...
I will be grateful and appreciate any tips or advice or if somebody solved the same issue in the past ....
Kuby
No, each error line of list in step List.Transform coud by extracted as new query and there are all records from one page OK. hmmmm
Finnaly, problem described in this issue was caused by "corrupted" content of returning json. The provider of core system informed me that they found bug and after fixing on the side of servisdesk is everything OK again. I tried to find problem in Power query and problem was in servisdesk. :(

Dexie.js - table.delete(id) not working for per-row deletion

i'm just starting out with Dexie, and I seem to be coming unstuck.
I have a small database (less than 1000 rows), and i'm trying to delete each row one-by-one once I know that the row has been sent to a remote API.
I can also successfully save to the table (which is defined by an ID and a column storing a serialised object)
here's my code:
if (online) {
//we query the db and send each event
database.open()
let allEvents = database.events.toCollection()
let total = allEvents.count(function (count) {
console.log(count + ' events in total')
//a simple test to ensure we're seeing the right number of records
})
allEvents.each(function(thisEvent){
//push to remote API
console.log('deleting ' + thisEvent.id)
database.events.delete(thisEvent.id) //<= this doesn't seem to be working
})
}
All of this with the exception of the final delete statement.
Any ideas on how I should fix this? the important thing for me is to delete on a per-row basis.
thanks in advance!
I was experiencing the same problem, and the answer from Eugenia Pais wasn't working for me. So after some tests, I saw the trouble was with the type of the variable: I was using a string, but a number is needed, so this is how I solved it:
function removeRow (primaryKey) {
primaryKey = parseInt(primaryKey);
databaseName.tableName.where('primaryKey').equals(primaryKey).delete().then(function(deleteCount) {
console.log ("Deleted " + deleteCount + " rows");
}).catch(function(error) {
console.error ("Error: " + error);
});
So be aware you are using a number as argument.
The correct way to delete each row should be selecting the specific row and delete it:
database.tableName.where(indexId).equals(indexValue).delete();
The data type of the key is not a problem you could verify it in my example here: example
db.example.where('key').equals('one').delete();
Maybe you are trying to delete by a property that not is an index.

Using Laravel 5, how do I get all() and order by belongsToMany relationship by the pivot table

I have Deals and Faq's. I have functional relationships working and I can reference $deal->faqs() and it returns the right faqs.
The problem I am trying to solve comes up as I administer the faqs related to a deal. In my Deal admin view (new / edit) I am getting all the Faq's.
$faqs = \App\Faq::all();
This works great, and I am even able to check if an faq is related to a deal through my checkbox: in the view:
{!! Form::checkbox('faqlist[]', $faq->id, $deal->faqs->contains($faq->id) ? true : false) !!}
So now we have a list of all the faqs and the correct ones are checked.
I have setup an order column on the pivot table (deal_faq). That table consists of:
deal_id
faq_id
timestamps
order
In my form, I have a drag and drop ordering solution (js) built and working. By working I mean, I can drag/drop and a hidden field value is updated to reflect the correct order.
When creating a deal, this is no problem. Get all the faq's, check a few to associate, drag to order, then save.
When editing a deal, I need to load based on the order column in the deal_faq table. This is my issue.
I have tried a few things but always get an error. An example of what I have tried is:
$faqs = \App\Faq::orderBy('deal_faq.order', 'asc')->get();
This returns an error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'deal_faq.order' in 'order clause' (SQL: select * from `faq` order by `deal_faq`.`order` asc)
I think the issue is that I am trying to get all, but order by a field that only exists for the related faqs since the order field is on the deal_faq. Just not sure how to solve.
In essence you need to join the pivot table and then apply the order
$faqs = \App\Faq::join('deal_faq', 'faqs.id', '=', 'deal_faq.faq_id')
->orderBy('deal_faq.order', 'asc')
->get();
You may need to adjust table and column names to match your schema.
Now you can extract this logic into a scope of the Faq model
class Faq extends Model
{
...
public function scopeOrdered($query)
{
return $query->join('deal_faq', 'faqs.id', '=', 'deal_faq.faq_id')
->orderBy('deal_faq.order', 'asc');
}
}
and then use it like this
$faqs = \App\Faq::ordered()->get();
UPDATE:
This works to get the FAQ's in order but it only get the ones that
have been associated. There will be FAQ's that are not associated and
thus not ordered.
In this case you just need to use an outer join - LEFT JOIN. The scope definition would then look like this
public function scopeOrdered($query)
{
return $query->join('deal_faq', 'faqs.id', '=', 'deal_faq.faq_id', 'left')
->orderBy('deal_faq.order', 'asc');
}
or a bit more expressively
public function scopeOrdered($query)
{
return $query->leftJoin('deal_faq', 'faqs.id', '=', 'deal_faq.faq_id')
->orderBy('deal_faq.order', 'asc');
}
Please consider adding a secondary order (i.e. by id, or any other field(s) in faqs table that make sense). This way you'd have a deterministically ordered resultsets each time regardless of whether you have an explicit order defined in a pivot table or not.

Loading Thousands of Codes to Map to a Shopping Cart Rule in Magento

I've been looking at the salesrule_coupon table, and I've discovered that I can map many coupon codes to a single rule, if the rule itself is of type 'Auto.' This is highly convenient as my client needs us to sync the codes periodically with a feed of data.
So in loading in these thousands of codes (using a custom module & direct SQL calls) they load just fine, and I can test and verify that many of them work.
However in working my way down the list of these codes, they stop working. The first 30 or so will work just fine, but thereafter, Magento says that the codes are invalid.
I'm still debugging this, and I'll post updates if I discover anything... but I've tried and experienced this with two separate price rules now. One rule crapped out at the 31st code, the second at the 39th.
What's really strange is that, if I change these codes to point to a different rule (one with less than 30 codes) they're recognized and accepted. Nothing else changed, that I can determine.
Any ideas on how to proceed here? Has anyone attempted this before? This is an interesting one.
I fixed the same issue when I was creating something similar for one of my customers. The source of the problem for retrieving of valid coupon Magento Core Sales Rule module uses FIND_IN_SET() with GROUP_CONCAT() MySQL functions instead adding additional condition for joined table. So FIND_IN_SET just truncates number of coupon codes that are used in group concatenation to 31 item (32 bits mask). Also I noticed that they are using HAVING instead of where, so it affects performance a bit.
So what you need to do are the following:
Create rewrite for this resource model: Mage_SalesRule_Model_Mysql4_Rule_Collection (salesrule/rule_collection)
Then in your resource model that rewrites core one, you need to redefine this method setValidationFilter($websiteId, $customerGroupId, $couponCode='', $now=null) that applies limitations for sales rules on the frontend. Here the method body that I used:
/**
* Fix for validation with auto-coupons
* #todo remove this fix, after the bug in core will be fixed
*
* (non-PHPdoc)
* #see Mage_SalesRule_Model_Mysql4_Rule_Collection::setValidationFilter()
*/
public function setValidationFilter($websiteId, $customerGroupId, $couponCode='', $now=null)
{
if (is_null($now)) {
$now = Mage::getModel('core/date')->date('Y-m-d');
}
$this->getSelect()->where('is_active=1');
$this->getSelect()->where('find_in_set(?, website_ids)', (int)$websiteId);
$this->getSelect()->where('find_in_set(?, customer_group_ids)', (int)$customerGroupId);
if ($couponCode) {
$couponCondition = $this->getConnection()->quoteInto(
'extra_coupon.code = ?',
$couponCode
);
$this->getSelect()->joinLeft(
array('extra_coupon' => $this->getTable('salesrule/coupon')),
'extra_coupon.rule_id = main_table.rule_id AND extra_coupon.is_primary IS NULL AND ' . $couponCondition,
array()
);
$this->getSelect()->where('('
. $this->getSelect()->getAdapter()->quoteInto(' main_table.coupon_type <> ?', Mage_SalesRule_Model_Rule::COUPON_TYPE_SPECIFIC)
. $this->getSelect()->getAdapter()->quoteInto(' OR primary_coupon.code = ?', $couponCode) . ')'
);
$this->getSelect()->where('('
. $this->getSelect()->getAdapter()->quoteInto(' main_table.coupon_type <> ?', Mage_SalesRule_Model_Rule::COUPON_TYPE_AUTO)
. $this->getSelect()->getAdapter()->quoteInto(' OR extra_coupon.code IS NOT NULL') . ')'
);
} else {
$this->getSelect()->where('main_table.coupon_type = ?', Mage_SalesRule_Model_Rule::COUPON_TYPE_NO_COUPON);
}
$this->getSelect()->where('from_date is null or from_date<=?', $now);
$this->getSelect()->where('to_date is null or to_date>=?', $now);
$this->getSelect()->order('sort_order');
return $this;
}
Test fix & Enjoy Magento Development :)
Another solution is to increase the mysql limit you are running into with
SET GLOBAL group_concat_max_len=9999999;
as Ivan explained the FIND_IN_SET does not return all your coupon codes. You need to increase group_concat_max_len to be able to hold the length of all your coupon codes delimited by a comma (COUPON1, COUPON2, COUPON3).
Since you have likely used different codes with different lengths, this would explain why 1 rule worked for 30 while the other worked for 38.

Preventing Doctrine's query cache in Symfony

In my Symfony/Doctrine app, I have a query that orders by RANDOM(). I call this same method several times, but it looks like the query's result is being cached.
Here's my relevant code:
$query = $table->createQuery('p')
->select('p.*, RANDOM() as rnd')
->orderBy('rnd')
->limit(1)
->useQueryCache(null)
->useResultCache(null);
$result = $query->fetchOne();
Unfortunately, the same record is returned every time, regardless of me passing null to both useQueryCache and useResultCache. I tried using false instead of null, but that didn't work either. Lastly, I also tried calling both setResultCacheLifeSpan(0) and setResultCacheLifeSpan(-1), but neither call made a difference.
Any insight on how to prevent caching since I want a different random row to be selected each time I call this method?
Edit: I also tried calling clearResultCache(), but that just ended up causing an error stating: "Result Cache driver not initialized".
Edit 2: As requested, here's the SQL generated by calling $query->getSqlQuery():
SELECT c.id AS c__id, c.name AS c__name, c.image_url AS c__image_url,
c.level AS c__level, c.created_at AS c__created_at, c.updated_at
AS c__updated_at, RANDOM() AS c__0 FROM cards c ORDER BY c__0 LIMIT 1
It turns out I'm a moron. I tried to simplify my query for this question, and in doing so, I didn't capture the true cause. I had a where() and andWhere() call, and the combination of conditions resulted in only one possible record being matched. Thanks for taking the time to respond, everyone, sorry to have wasted your time!
Doctrine also caches entities you created in the same request/script run.
For instance:
$order = new Order();
$order->save();
sleep(10); // Edit this record in de DB in another procces.
$q = new Doctrine_Query();
$result = $q->select()
->from('Order o')
->where('o.id = '.$order->id);
$order = $result->getFirst();
print_r($order->toArray());
The print_r will not contain the changes you made during the sleep.
The following code will remove that kind of memory cache:
$manager = Doctrine_Manager::getInstance();
$connection = $manager->getCurrentConnection();
$tables = $connection->getTables();
foreach ( $tables as $table ) {
$table->clear();
}
PS: Added this answer because I found this topic trying to resolve above issue.

Resources