laravel 5 - paginate total() of a query with distinct - pagination

I have a query to get photos according to values in a pivot table, that stores the relation of "pics" and "tags":
#photos
$q = PicTag::select(DB::raw('distinct(pics.id)'),
'pics.url',
'pics.titel',
'pics.hits',
'pics.created_at',
'users.username',
'users.displayname')
->leftJoin('pics', 'pics.id', '=', 'pic_tag.pic_id')
->leftJoin('users','users.id','=','pics.user_id')
->whereIn('pic_tag.tag_id', $tagids);
if($cat)
$q->where('typ',$cat);
if($year)
$q->where('jahrprod',$year);
$pics = $q->orderBy('pics.id','desc')
->paginate(30);
The problem is, when for a certain photo multiple (same) tags are stored like "Tag", "tag" and "tAG". Then the same photo would be shown 3 times in my gallery. That is why I use the distinct in the query.
Then the gallery is ok, but $pics->total() does not show "87 photos" but for example "90 photos", because the distinct is not used in the pagination. In laravel 4, I used groupBy('pics.id'), but this did not seem to be the fastest query and with laravel 5 it gives me a total() count result of 1.
How could I get the right total() value?

I know it's an old subject but it could help some other people.
I faced the same problem and the only good solution (low memory cost) I found was to do the request in two times:
$ids = DB::table('foo')
->selectRaw('foo.id')
->distinct()
->pluck('foo.id');
$results = $query = DB::table('foo')
->selectRaw('foo.id')
->whereIn('foo.id', $ids)
->paginate();
I tried this with 100k results, and had no problem at all.

Laravel has issue in paginate of complex queries. so you should handle them manually . In laravel 5 I did it in 2 steps :
Step 1: repository method :
public function getByPage($page = 1, $limit = 10 , $provinceId , $cityId , $expertiseId)
{
$array = ['users.deleted' => false];
$array["users.approved"] = true;
$array["users.is_confirmed"] = true;
if($provinceId)
$array["users.province_FK"] = $provinceId;
if($cityId)
$array["users.city_FK"] = $cityId;
if($expertiseId)
$array["ONJNCT_USERS_EXPERTISE.expertise_FK"] = $expertiseId;
$results = new \stdClass();
$results->page = $page;
$results->limit = $limit;
$results->totalItems = 0;
$results->items = array();
$users= DB::table('users')
->distinct()
->select('users.*','ONDEGREES.name as drgree_name')
->join('ONJNCT_USERS_EXPERTISE', 'users.id', '=', 'ONJNCT_USERS_EXPERTISE.user_FK')
->join('ONDEGREES', 'users.degree_FK', '=', 'ONDEGREES.id')
->where($array)
->skip($limit * ($page - 1))->take($limit)->get();
//$users = $usersQuery>skip($limit * ($page - 1))->take($limit)->get();
$usersCount= DB::table('users')
->select('users.*','ONDEGREES.name as drgree_name')
->join('ONJNCT_USERS_EXPERTISE', 'users.id', '=', 'ONJNCT_USERS_EXPERTISE.user_FK')
->join('ONDEGREES', 'users.degree_FK', '=', 'ONDEGREES.id')
->where($array)
->count(DB::raw('DISTINCT users.id'));
$results->totalItems = $usersCount;
$results->items = $users;
return $results;
}
Step 2:
In my Search Controller :
function search($provinceId , $cityId , $expertiseId){
$page = Input::get('page', 1);
$data = $this->userService->getByPage($page, 1 , $provinceId ,$cityId , $expertiseId);
$users = new LengthAwarePaginator($data->items, $data->totalItems, 1 , Paginator::resolveCurrentPage(),['path' => Paginator::resolveCurrentPath()]);
return View::make('guest.search.searchResult')->with('users' ,$users);
}
It worked for me well!

Related

Different approach for pagination - LIMIT when using SQLSRV

I'm trying to make an instant pagination using SQLSRV and PHP, I have successfully did this using MySQL but unable to do so when using SQL Server as it does not support LIMIT.
I have the following codes working in MySQL and I wanted to apply the same thing in sqlsrv but since this is not possible, I'm looking forward in creating a different approach(code) to achieve this, can someone give me an idea or a walkthrough to make this happen please, thanks in advanced.
if(isset($_POST['page'])):
$paged=$_POST['page'];
$sql="SELECT * FROM `member` ORDER BY `member`.`member_id` ASC";
if($paged>0){
$page_limit=$resultsPerPage*($paged-1);
$pagination_sql=" LIMIT $page_limit, $resultsPerPage";
}
else{
$pagination_sql=" FETCH 0 , $resultsPerPage";
}
$result=sqlsrv_query($sql.$pagination_sql);
Try the following code, I hope you find it helpful
$paged = filter_input(INPUT_POST, 'page', FILTER_SANITIZE_NUMBER_INT);
//Initialize these values
$Table = 'your_tbl_name'; //Table name
$IndexColumn = 'pk_col_name'; //Primary key column
$resultsPerPage = '10'; //Page size
$Where = ''; //Optional WHERE clause, may leave empty
$Order = ''; //Optional ORDER clause, may leave empty
$top = ($paged>0) ? $resultsPerPage * ($paged-1) : 0 ;
$limit = 'TOP ' . $resultsPerPage ;
$pagination_sql = "SELECT $limit *
FROM $Table
$Where ".(($Where=="")?" WHERE ":" AND ")." $IndexColumn NOT IN
(
SELECT $IndexColumn FROM
(
SELECT TOP $top *
FROM $Table
$Where
$Order
)
as [virtTable]
)
$Order";
$result=sqlsrv_query($conn, $pagination_sql);

complex entityframework query

I have two tables:
NewsRooms ( NrID[int] , NrName [string]);
RawNews( RnID [int], NrID[string]);
realtion is RawNews 1 * NewsRooms
so i use checkboxes for NewsRooms and save the ids as a string in RawNews like this ';1;2;'
now for example i have a list which contains some NrIDs . i want to select every RawNew which it's NrID contains any of the ids inside that list.
here is my code:
var temp = Util.GetAvailibleNewsRooms("ViewRawNews");
List<string> ids = new List<string>();
foreach (var item in temp)
ids.Add(";" + item.NrID.ToString() + ";");
model = db.RawNews.Where(r => r.NrID.Any(ids));
the line model = db.RawNews.Where(r => r.NrID.Any(ids)); is wrong and i don't know how to write this code. please guide me. thanks
ok guys, i found the solution myself so i post it here maybe some other guy need it some day!!
model = model.Where(r => ids.Any(i => r.NrID.Contains(i)));

MongoDB Geospatial query result not getting in order of Distance

I am new to mongodb, trying to fetch result from mongodb using geospatial.
With this [http://jamesroberts.name/blog/2012/03/12/mongodb-geospatial-query-example-in-php-with-distance-radius-in-miles-and-km/][1] reference, I created 2d indexer on my collection.
I am getting result but not getting in sorted order of Distance.
I tried $near operator also but it returns 100 documents. I want all result near by given location under given miles
Can anyone please help me to get data in sorted order of distance?
$connection = new MongoClient( "mongodb://192.168.1.167" );
$dbname="mydb";
$collectionName="user";
$db = $connection->$dbname;
$collection = $db->$collectionName;
$lat="36.23304900";
$lon="-115.24228800";
$radius = 40;
$collection = $db->$collectionName;
$radiusOfEarth = 3956; //avg radius of earth in miles
$query = array('lnglat' =>array('$geoWithin' =>array('$centerSphere' =>array(array(floatval($lon), floatval($lat)), $radius/$radiusOfEarth))) ,'user_id' => "1234" ,'type'=>"my_type");
$cursor = $collection->find($query);
Try This:
$cursor = $collection->find($query);
$cursor->sort(array('distance' => -1));

Drupal 7 - Ubercart - Attributes in Views Fields

I have products that have attributes for 'color' & 'strength'. I'm trying to get those options listed under those attributes as fields for views, so that I can use them as filters. So for example sort by color & strength.
I've looked all around on google and can only find modules for Drupal 6. Anyone know of anything for 7?
Like said in the previous post I had 2 attributes 'color' & 'strength' which I needed to match for exact product matches but ubercart didn't have anything for that, so I wrote them into URL for get statements as variables 1 & 2, so for example a URL which had both attributes selected would look like:
www.website.com/node/68?1=96&2=7
Sometimes one variable would be set but not the other, so I had to make up for that also by using a % wildcard. Here's the code for that part
// Since PHP's serialize function sometimes serializes in the incorrect order,
// here we manually build the comparison key
// Additionally append the image links urls with provided strength/color data
if( isset( $_REQUEST['1'] ) ) {
$_1 = $_REQUEST['1'];
if( $_1 !== '%' ) $url[] = "1=$_1";
} else $_1 = '%';
if( isset( $_REQUEST['2'] ) ) {
$_2 = $_REQUEST['2'];
if( $_2 !== '%' ) $url[] = "2=$_2";
} else $_2 = '%';
$combination = "a:2:{i:1;s:";
$combination .= $_1 == '%' ? '%:"%";' : strlen($_1) . ':"' . $_1 . '";';
$combination .= "i:2;s:";
$combination .= $_2 == '%' ? '%:"%";' : strlen($_2) . ':"' . $_2 . '";';
$combination .= '}';
// if some products don't have a second attribute at all
$combination2 = "a:1:{i:1;s:";
$combination2 .= $_1 == '%' ? '%:"%"' : strlen($_1) . ':"' . $_1 . '";';
$combination2 .= ';}';
Underneath that I had to do some extra queries like if a taxonomy was set and check if some dynamic properties were set, thats why the WHERE is stored in a variable. Frankly they'll just confuse anyone so I left them out. But for your sake the next part you just need to query it.
$where = "WHERE (pa.combination LIKE :pattern1 OR pa.combination LIKE :pattern2) AND s.stock IS NOT NULL";
$comparison = array( ':pattern1' => $combination,
':pattern2' => $combination2 );
$filtered = db_query(
"
SELECT pa.nid, pa.model, pa.combination, n.title, p.sell_price, f.uri
FROM {uc_product_adjustments} pa
LEFT JOIN {node} n ON pa.nid = n.nid
LEFT JOIN {uc_products} p ON pa.nid = p.nid
LEFT JOIN {field_data_uc_product_image} i ON i.entity_type = 'node' AND i.entity_id = n.nid
LEFT JOIN {file_managed} f ON f.fid = i.uc_product_image_fid
LEFT JOIN {uc_product_stock} s ON pa.model = s.sku AND s.stock <> '0'
$where
",
$comparison
);
Lastly loop over the results and store them in a normal array
foreach( $filtered as $i => $record ) {
if( is_int( array_search( $record->nid, $nids ) ) ) continue;
else {
$nids[] = $record->nid;
$result[] = $record;
}
}
This code checks for any products that match any of the attribute values that are currently in stock
You may have a look at these sandbox projects : UC Views Attributes Work and UC attribute views.
I'm looking for a similar feature, as it seems not possible to get UC attributes into a view. I cannot test myself right now as I have a deadline this weekend for a project, but I'd be happy to have your feedback.

FullTextSqlQuery RowLimit setting defaulted when adding WHERE criteria

We are experiencing an issue where a FullTextSqlQuery is only returning the default 100 results whenever certain criteria are added in the WHERE clause. We are setting the RowLimit to int.MaxValue, and when a wide-open search is done, we are receiving the max results. It's only an issue when tacking-on CONTAINS clauses. Has anyone else seen this issue? I wasn't able to dig up anything on Google/Bing.
FullTextSqlQuery kRequest = new FullTextSqlQuery(ServerContext.Current);
kRequest.KeywordInclusion = KeywordInclusion.AnyKeyword;
kRequest.ResultTypes = ResultType.RelevantResults;
kRequest.TrimDuplicates = false;
kRequest.RowLimit = int.MaxValue;
kRequest.Timeout = 120000;
ResultTableCollection resultTbls = kRequest.Execute();
Query Code:
string query = "SELECT Title, Path, Facility, OwnerDepartment,
FacilityActiveDate, FacilityInactiveDate, ScheduledReviewDate, DocID,
Version FROM SCOPE() WHERE ";
query += "Path like '%" + site.Url + "%'";
// when it hits the else statement is an example of when it will only
// return 100 results
if (FacilitySelectedIndex == 1)
{
query += " AND Facility IS NOT NULL";
}
else
{
query += " AND CONTAINS(Facility, '\"*" + FacilityShortName.Trim() + "*\"')";
queryText.Add("Facility=" + FacilityShortName);
}
}
If I recall correctly, the RowLimit max value is actually less than int.MaxValue, only it won't tell you that. Try setting the RowLimit to some arbitrary large number that is still smaller than int.MaxValue, such as 99999

Resources