FQL - EVENT table - events

When using the the "Graph API Explorer":
SELECT name FROM event
WHERE eid IN (
SELECT eid FROM event_member WHERE uid = 207255995711
)
ORDER BY start_time DESC
everything is fine & works. But when I try to run the fql-query on my server, it returns an empty Array.
Only 50% of the UIDs don't work. When I use 155326044518189 instead of the 207255995711, everything works fine.
Both are set on OPEN / PUBLIC. But only works in the "Graph API Explorer" 100%
Steps to reproduce, try to get some output with this piece of code:
<?php
require 'facebook_lib/facebook.php';
require 'facebook_lib/config.php';
try {
$fql = "SELECT name FROM event
WHERE eid IN (
SELECT eid FROM event_member WHERE uid = 207255995711
)
ORDER BY start_time DESC";
$param = array(
'method' => 'fql.query',
'query' => $fql,
'callback' => ''
);
$fqlResult = $facebook->api($param);
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
foreach($fqlResult as $keys => $values):
echo $values['name'];
echo '<br>';
endforeach;
?>
http://lab.daniel-walter.com/facebook2/facebook.php

Related

Avoiding repeated data in laravel querybuilder result

I am trying to write code to return the number of diseases diagnosed in a clinic after a given period either weekly, monthly or daily using jimmyjs laravel-report-generator using the code bellow,
$fromDate = $request->fromDate;
$toDate = $request->toDate;
$sortBy = 'updated_at';
$title = 'CHATTHE GROUP'; // Report title
$subTitle = 'Mobidity Report';
$total = 0;
$meta = [ // For displaying filters description on header
''=> $subTitle,
'From' => $fromDate . ' To: ' . $toDate,
'Generated By' => Auth::user()->name
];
$queryBuilder = Diagnosis::select(['diagnosis', 'updated_at']) // Do some querying..
->whereBetween('updated_at', [$fromDate, $toDate])
->distinct('diagnosis')
->orderBy($sortBy, 'ASC');
$columns = [ // Set Column to be displayed
'DISEASE' => 'diagnosis',
'NO OF CASES' => function($result){
return Diagnosis::where('diagnosis',$result->diagnosis)->count();
}, // if no column_name specified, this will automatically seach for snake_case of column name (will be registered_at) column from query result
'% TOTAL' => function($result){
return (Diagnosis::where('diagnosis',$result->diagnosis)->count()/$result->count()*100);
}
];
return ExcelReport::of($title, $meta, $queryBuilder, $columns)
->editColumns(['DISEASE', '% TOTAL'], [ // Mass edit column
'class' => 'right bold'
])
->showHeader(true)
->simple()
->download('mobidityReport');
This produces the following excel file
Which has the diseases repeated just as they repeat in the table, is there anyway to avoid this? I tried using distinct() but that gave an error.

How to update multiple rows from a single query using eloquent/fluent?

I was learning about How to insert multiple rows from a single query using eloquent/fluent and I found the answer here
Can somebody share any documentation about how to update bulk rows in single query?
My queries are below.
Update tblrole set role = 'Super Admin' where RoleID = 1;
Update tblrole set role = 'Super Admin A' where RoleID = 2;
Update tblrole set role = 'Super Admin B' where RoleID = 3;
Update tblrole set role = 'Super Admin C' where RoleID = 4;
You can solve the issue using a single MySQL query. It can be implemented in Laravel Eloquent using DB::raw() method.
**UPDATE** tblrole **SET** role =
**CASE**
WHEN RoleID = 1 THEN 'Super Admin'
WHEN RoleID = 2 THEN 'Super Admin A'
WHEN RoleID = 3 THEN 'Super Admin B'
WHEN RoleID = 4 THEN 'Super Admin C'
**END**
**WHERE** RoleID in (1,2,3,4);
You cannot do anything like this in simple way. You can easily update multiple rows with same value but if you want to update role column with different values it will be tricky.
In fact it doesn't make much sense to do it like this but if you really want it and you think it's the best solution you can try to play with raw queries using technique described here https://stackoverflow.com/a/25674827/3593996
You might find inspiration from this mass insert or update gist:
/**
* Mass (bulk) insert or update on duplicate for Laravel 4/5
*
* insertOrUpdate([
* ['id'=>1,'value'=>10],
* ['id'=>2,'value'=>60]
* ]);
*
*
* #param array $rows
*/
function insertOrUpdate(array $rows){
$table = \DB::getTablePrefix().with(new self)->getTable();
$first = reset($rows);
$columns = implode( ',',
array_map( function( $value ) { return "$value"; } , array_keys($first) )
);
$values = implode( ',', array_map( function( $row ) {
return '('.implode( ',',
array_map( function( $value ) { return '"'.str_replace('"', '""', $value).'"'; } , $row )
).')';
} , $rows )
);
$updates = implode( ',',
array_map( function( $value ) { return "$value = VALUES($value)"; } , array_keys($first) )
);
$sql = "INSERT INTO {$table}({$columns}) VALUES {$values} ON DUPLICATE KEY UPDATE {$updates}";
return \DB::statement( $sql );
}
Ref: https://gist.github.com/RuGa/5354e44883c7651fd15c
I don't think I need to provide any explanation as each chunk of code in the function speaks of itself.

Magento Changing Default Payment Method

I have a function that runs raw SQL queries to our database in Magento. What the function does is changes the customer's default credit card to a value passed to the function. My question is how would I rewrite the function utilizing Magento models. The current function works, but we'd rather have it not be directly interfacing with SQL.
Here is the function:
public function setDefaultPayment($value)
{
$customerId = $this->_getSession()->getCustomer()->getId();
$write = Mage::getSingleton('core/resource')->getConnection('core_write');
$read = $write->query("SELECT entity_type_id FROM eav_entity_type WHERE entity_type_code='customer'");
$row = $read->fetch();
$entity_type_id = $row['entity_type_id'];
$read = $write->query("SELECT attribute_id FROM eav_attribute WHERE attribute_code='default_payment' AND entity_type_id = $entity_type_id");
$row = $read->fetch();
$attribute_id = $row['attribute_id'];
$read = $write->query("SELECT * FROM customer_entity_int WHERE entity_type_id='$entity_type_id' AND attribute_id='$attribute_id' AND entity_id='$customerId'");
if ($row = $read->fetch()) {
$write->update(
'customer_entity_int',
array('value' => $value),
"entity_type_id='$entity_type_id' AND attribute_id='$attribute_id' AND entity_id='$customerId'"
);
} else {
$write->insert(
'customer_entity_int',
array(
'entity_type_id' => $entity_type_id,
'attribute_id' => $attribute_id,
'entity_id' => $customerId,
'value' => $value
)
);
}
}
If I read you code right, you want to update the customer attribute default_payment with a value given.
For that you need to:
Load the customer by id
Set the new value for the customer attribute default_payment
Save the customer
public function setDefaultPayment($value)
{
$customerId = $this->_getSession()->getCustomer()->getId();
$write = Mage::getSingleton('core/resource')->getConnection('core_write');
$customer = Mage::getModel('customer/customer')->load($customerId);
$oldValue = $customer->getDefaultPayment(); // optional, just for checking
$customer->setDefaultPayment($value);
$customer->save();
}

Laravel Bulk UPDATE

I'm trying to update a table containing a slug value with random slugs for each record.
$vouchers = Voucher->get(); // assume 10K for example
foreach ($vouchers as $voucher) {
$q .= "UPDATE vouchers set slug = '" . Str::random(32) . "' WHERE id = " . $voucher->id . ";";
}
DB::statement($q);
There are about 2 million records so I need to perform this as a bulk. Doing it as separate records is taking way too long. I can't seem to find a way to bulk run them, say in groups of 10K or something.
Tried a bunch of variations of ->update() and DB::statement but can't seem to get it to go.
In case someone land in this page like me, laravel allows a bulk update as:
$affectedRows = Voucher::where('id', '=', $voucher->id)->update(array('slug' => Str::random(32)));
See "Updating A Retrieved Model" under http://laravel.com/docs/4.2/eloquent#insert-update-delete
I have created My Custom function for Multiple Update like update_batch in CodeIgniter.
Just place this function in any of your model or you can create helper class and place this function in that class:
//test data
/*
$multipleData = array(
array(
'title' => 'My title' ,
'name' => 'My Name 2' ,
'date' => 'My date 2'
),
array(
'title' => 'Another title' ,
'name' => 'Another Name 2' ,
'date' => 'Another date 2'
)
)
*/
/*
* ----------------------------------
* update batch
* ----------------------------------
*
* multiple update in one query
*
* tablename( required | string )
* multipleData ( required | array of array )
*/
static function updateBatch($tableName = "", $multipleData = array()){
if( $tableName && !empty($multipleData) ) {
// column or fields to update
$updateColumn = array_keys($multipleData[0]);
$referenceColumn = $updateColumn[0]; //e.g id
unset($updateColumn[0]);
$whereIn = "";
$q = "UPDATE ".$tableName." SET ";
foreach ( $updateColumn as $uColumn ) {
$q .= $uColumn." = CASE ";
foreach( $multipleData as $data ) {
$q .= "WHEN ".$referenceColumn." = ".$data[$referenceColumn]." THEN '".$data[$uColumn]."' ";
}
$q .= "ELSE ".$uColumn." END, ";
}
foreach( $multipleData as $data ) {
$whereIn .= "'".$data[$referenceColumn]."', ";
}
$q = rtrim($q, ", ")." WHERE ".$referenceColumn." IN (". rtrim($whereIn, ', ').")";
// Update
return DB::update(DB::raw($q));
} else {
return false;
}
}
It will Produces:
UPDATE `mytable` SET `name` = CASE
WHEN `title` = 'My title' THEN 'My Name 2'
WHEN `title` = 'Another title' THEN 'Another Name 2'
ELSE `name` END,
`date` = CASE
WHEN `title` = 'My title' THEN 'My date 2'
WHEN `title` = 'Another title' THEN 'Another date 2'
ELSE `date` END
WHERE `title` IN ('My title','Another title')
Chunking results is the best way to do this kind of stuff without eating all of your RAM and Laravel support chunking results out of the box.
For example:
Voucher::chunk(2000, function($vouchers)
{
foreach ($vouchers as $voucher)
{
//
}
});
I made a bulk update function to use in my Laravel projects. It may be useful for anyone who wants to use the batch update query in Laravel. Its first parameter is the table name string, second is the key name string based on which you want to update the row or rows and most of the times it will be the 'id' and the third parameter is a data array in the following format:
array(
array(
'id' => 1,
'col_1_name' => 'col_1_val',
'col_2_name' => 'col_2_val',
//...
),
array(
'id' => 2,
'col_1_name' => 'col_1_val',
'col_2_name' => 'col_2_val',
//...
),
//...
);
The function will return the number of affected rows. Function definition:
private function custom_batch_update(string $table_name = '', string $key = '', Array $update_arr = array()) {
if(!$table_name || !$key || !$update_arr){
return false;
}
$update_keys = array_keys($update_arr[0]);
$update_keys_count = count($update_keys);
for ($i = 0; $i < $update_keys_count; $i++) {
$key_name = $update_keys[$i];
if($key === $key_name){
continue;
}
$when_{$key_name} = $key_name . ' = CASE';
}
$length = count($update_arr);
$index = 0;
$query_str = 'UPDATE ' . $table_name . ' SET ';
$when_str = '';
$where_str = ' WHERE ' . $key . ' IN(';
while ($index < $length) {
$when_str = " WHEN $key = '{$update_arr[$index][$key]}' THEN";
$where_str .= "'{$update_arr[$index][$key]}',";
for ($i = 0; $i < $update_keys_count; $i++) {
$key_name = $update_keys[$i];
if($key === $key_name){
continue;
}
$when_{$key_name} .= $when_str . " '{$update_arr[$index][$key_name]}'";
}
$index++;
}
for ($i = 0; $i < $update_keys_count; $i++) {
$key_name = $update_keys[$i];
if($key === $key_name){
continue;
}
$when_{$key_name} .= ' ELSE ' . $key_name . ' END, ';
$query_str .= $when_{$key_name};
}
$query_str = rtrim($query_str, ', ');
$where_str = rtrim($where_str, ',') . ')';
$query_str .= $where_str;
$affected = DB::update($query_str);
return $affected;
}
It will produce and execute the query string like this:
UPDATE table_name SET col_1_name = CASE
WHEN id = '1' THEN 'col_1_value'
WHEN id = '2' THEN 'col_1_value'
ELSE col_1_name END,
col_2_name = CASE
WHEN id = '1' THEN 'col_2_value'
WHEN id = '2' THEN 'col_2_value'
ELSE col_2_name END
WHERE id IN('1','2')

Magento 'customer_login' event not catched [duplicate]

This question already has answers here:
How do I create a Magento session outside of Magento?
(4 answers)
Closed 7 years ago.
I nave a issue with customer login event. I have application (flex app) outside magento and there is a form for customer login. I use this code to login customers:
require_once '../../app/Mage.php';
umask(0);
Mage::app();
Mage::getSingleton('core/session', array('name'=>'frontend'));
$session = Mage::getSingleton('customer/session');
try {
$session->login ( $_REQUEST['username'], $_REQUEST['password'] );
$return .= '<userid>'.$session->getCustomer()->getId().'</userid>';
} catch (Exception $e) {
$return .= '<error>'.$e->getMessage().'</error>';
}
Everything works well and the customer is logged in. The issue is that the event is dispatched but Mage::Visitor and Mage::Reports does't catch the event and if I return from flex to product view page it gets MySQL errors in the "report_viewed_product_index" table. Can anyone help with this.
Thank you!
Solved my issue reading How do I create a Magento session outside of Magento?
Here is what I've done
require_once '../../app/Mage.php';
umask(0);
Mage::app($_REQUEST['store_id'])->init();
$core_session = Mage::getSingleton('core/session', array('name'=>'frontend'));
$session = Mage::getSingleton('customer/session');
$return = '<user>';
$write = Mage::getSingleton ( 'core/resource' )->getConnection ( 'core_write' );
$url = Mage::getUrl ( '*/*/*', array ('_current' => true ) );
Mage::getSingleton ( 'core/session' )->setLastUrl ( $url );
$visitor_id = $_SESSION ['core'] ['visitor_data'] ['visitor_id'];
if (! empty ( $visitor_id )) {
Mage::getSingleton ( 'log/visitor' )->setId ( $visitor_id );
} else {
Mage::getSingleton ( 'customer/session' )->setWishlistItemCount ( 0 );
Mage::getSingleton ( 'catalog/session' )->setCatalogCompareItemsCount ( 0 );
$write->query ( "INSERT INTO log_url_info (url, referer) VALUES (?, ?)", array ($url, Mage::helper ( 'core/http' )->getHttpReferer ( true ) ) );
$url_id = $write->lastInsertId ();
$log_visitor = Mage::getSingleton ( 'log/visitor' )->initServerData ()->setFirstVisitAt ( now () )->setIsNewVisitor ( true )->setLastVisitAt ( now () )->setLastUrlId ( $url_id )->save ();
$write->query ( "INSERT INTO log_url (url_id, visitor_id, visit_time) VALUES (?, ?, ?)", array ($url_id, $log_visitor->getId (), now () ) );
$core_session->setVisitorData ( $log_visitor->getData () );
$visitor_id = $log_visitor->getId ();
}
try {
$session->login ( $_REQUEST['username_cl_mag'], $_REQUEST['password_cl_mag'] );
//$session->setCustomerAsLoggedIn($session->getCustomer());
//$customer = Mage::getModel('customer/customer')->setWebsiteId(Mage::app()->getStore()->getWebsiteId());
$customerId = $session->getCustomerId();
$eventModel = Mage::getModel('reports/event');
$eventModel->updateCustomerType($visitor_id, $customerId);
Mage::getModel('reports/product_index_compared')
->updateCustomerFromVisitor()
->calculate();
Mage::getModel('reports/product_index_viewed')
->updateCustomerFromVisitor()
->calculate();
$return .= '<userid>'.$session->getCustomerId().'</userid>';
} catch (Exception $e) {
$return .= '<error>'.$e->getMessage().'</error>';
}
print $return .= "</user>";

Resources