for ($i = 0; $i < count($keyskill); $i++) {
if ($i == count($keyskill) - 1) {
$key .= "skills like '%" . $keyskill[$i] . "%' ";
} else {
$key .= "skills like '%" . $keyskill[$i] . "%' or ";
}
}
Hear my Query is
$jobs = DB::select("SELECT * from post where ( $key ) and status=1 order by id desc");
How to write laravel model based in this query with pagination???
Post::where('skills' , 'like' , '%php%')->orWhere('skills' , 'like' , '%javascript%')->where('status' , 1)->orderBy('id' , 'desc')->paginate(10);
try this for dynamic array:
Post::where(function ($query) use ($keyskill) {
for ($i = 0; $i < count($keyskill); $i++) {
if ($i == 0) {
$query->where('skills' , 'like' ,"%$keyskill[$i]%");
} else {
$query->orWhere('skills' , 'like' , "%$keyskill[$i]%");
}
}
})->where('status' , 1)->orderBy('id' , 'desc')->paginate(10);
Below is the Eloquent Query considering Post as your Model Name and Page Size 50.
$posts = \App\Post::where('skills','like','%javascript%')
->orWhere('skills','like','%php%')
->where('status',1)
->orderBy('id','desc')
->paginate(50);
Loading records
$posts->items();
Rendering Pagination on Blade
{!! $posts->render() !!}
Just a recommendation
Your table name should be posts instead or post then Laravel can manage it implicitly but in your case currently you will have to mention the table name in your model with code protected $table = 'post'; in your app/post.php file, read more here.
Related
I want to work on a while loop in a foreach loop but I can't convert it to Laravel controller system. Please help.
foreach (range('a', 'z') as $i)
{
echo $i = strtolower($i);
$sql = "SELECT * FROM `list` Where name like '$i%' Limit 30";
$result = mysqli_query($con, $sql);
echo"<hr><h3>Name Starting with ".strtoupper($i)."</h3>";
while($row=mysqli_fetch_array($result,MYSQLI_ASSOC))
{
$id = $row['id'];
$name = $row['name'];
echo "<li>".$row['name']."</li>";
}
echo "<li>More</li>";
echo "</ul>";
}
The code in Laravel that I have is
foreach (range('a', 'z') as $i)
{
$list = DB::table('list')->where('name', 'LIKE', $i.'%')->limit(30)->get();
return view('pages.all', ['list' => $list]);
}
This code only gives data for names starting with alphabet "a" but won't proceed with the rest of the characters.
Store it on the array based on your search.
$list = array();
foreach (range('a', 'z') as $i) {
$list[$i] = DB::table('list')->where('name', 'LIKE', $i.'%')->limit(30)->get();
}
return view('pages.all', ['list' => $list]);
Customize your view, to showing the list against each character (a-z).
[Edit]
View file can be changed like below,
#foreach ($list as $keyI => $moredata)
<hr>
<h3>Author's Name Starting with "{{strtoupper($keyI)}}"</h3>
<ul class="tags-list">
#foreach ($moredata as $data)
<li>{{$data->name}}</li>
#endforeach
</ul>
#endforeach
My model:
function get_data($id)
{
$this->db->select('id, Company, JobTitle');
$this->db->from('client_list');
$this->db->where('id', $id);
$query = $this->db->get();
return $query->result();
}
I want to get the the data from get_data(), is this the right way?
public function show_data( $id )
{
$data = $this->get_data($id);
echo '<tr>';
echo '<td>'.$data['Company'].'</td>';
echo '<td>'.$data['JobTitle'].'</td>';
echo '<td>'.$data['id'].'</td>';
echo '<td></td>';
echo '</tr>';
}
Use the row_array() function to get the data in the array format.
Reference url
http://ellislab.com/codeigniter/user-guide/database/results.html
you can use foreach loop to print
foreach ($data->result() as $row)
{
echo '<tr>';
echo '<td>'.$row['Company'].'</td>';
echo '<td>'.$row['JobTitle'].'</td>';
echo '<td>'.$row['id'].'</td>';
echo '<td></td>';
echo '</tr>';
}
thank you
just to improve answer, I use "general_model" for all my controllers, there are some exceptions where I need special queries, I just create desired model so "general_model" stays same and I can use it in any project.
e.g.
general_model.php
function _getWhere($table = 'table', $select = 'id, name', $where = array()) {
$this->db->select($select);
$q = $this->db->get_where('`'.$table.'`', $where);
return ($q->num_rows() > 0) ? $q->result() : FALSE;
}
.
.
.
//bunch of another functions
in controller I just call
$this->data['books'] = $this->general_model->_getWhere('book', '*', array('active' => '1'));
$this->render('book_list_view'); // $this->load->view('book_list_view', $this->data);
sidenote: I am extending CI_Controller therefore I use $this->data['books'] instead $data['books'] to pass data into view
in view
//check if there are any data
if ($books === FALSE) {
//some error that there are no books yet
} else {
//load data to table or something
foreach ($books as $book) {
$book->id; // book id
}
}
public function search($query, $limit) {
// output
$output = "";
// query
$this->db->select("*");
$this->db->from("products");
$this->db->like("brand", $query);
$this->db->or_like("model", $query);
$this->db->limit($limit);
$query = $this->db->get();
// zero
if ($query->num_rows() == 0) {
$output .= "No results found";
return $output;
}
// result
foreach ($query->result_array() as $row) {
// uri
$uri2 = "{$this->base_url}specifications/{$row['brand']}-{$row['model']}";
$uri2 = str_replace(" ", "-", $uri2);
// price format
$row['price'] = number_format($row['price']);
// image url
$image = "{$this->base_url}assets/images/products/{$row['category']}-{$row['brand']}-{$row['model']}/thumb.png";
$image = str_replace(" ", "-", $image);
$output .= "<ul class=\"product\">\n
<a href=\"{$uri2}\">\n
<li class=\"product-image\"><img src=\"{$image}\" height=\"108\" width=\"57\" alt=\"\"></li>\n
<li class=\"product-brand\">{$row['brand']}</li>\n
<li class=\"product-model\">{$row['model']}</li>\n
<li class=\"product-price\">{$row['price']} <span class=\"green\">pkr</span></li>\n
</a>\n
</ul>\n";
}
// return
return $output;
}
Here I do three types of queries:
1- query that contains only brand (i get results)
2- query that contains only model (i get results)
3- query that contains both (i get no results)
How to accomplish the all above three tasks?
It seems that you are performing some kind of search, so the there result that you want to get are coming from controller or view, you jst do that make there if condition like this then do it as
if ($brand_val != '' )
{ //put your where query here }
if ($model_val != '' )
{ //put your where query here }
if ($brand_val != '' && $model_val != '' )
{ //put your where query here }
hope this will give idea
use this to print the query.
echo $this->db->last_query();
and then try execute that query in your phpmyadmin
I built this method following the the tagged() method from blog module
public function genres($genre = null)
{
$this->db->order_by('name', 'ASC');
$result = $this->db->get('keywords');
$genres = $result->result();
if($genre)
{
$this->load->model('genres_m');
// decode encoded cyrillic characters
$genre = rawurldecode($genre) OR redirect('generos');
$time[] = time();
// Count total blog posts and work out how many pages exist
$pagination = create_pagination(lang('ebooks:routes:genres') . '/' . $genre, $this->genres_m->count_genres_by($genre, array('entry_active' => 1)), NULL, 4);
$time[] = time();
// Get the current page of blog posts
$books = $this->genres_m
->limit($pagination['per_page'])
->order_by('info_title', 'ASC')
->get_genres_by($genre, array('entry_active' => 1));
$time[] = time();
foreach ($books AS &$book)
{
$book->books_info_genre = Keywords::get($book->books_info_genre, 'blog/tagged');
$book->url = site_url(lang('ebooks:routes:ebook') . '/' . $book->info_title . '/' . $book->id);
}
$time[] = time();
// Set meta description based on post titles
//$meta = $this->_posts_metadata($books);
$name = str_replace('-', ' ', $genre);
// Build the page
$this->template
->title($this->_template_title(lang('ebooks:of').' '.$name))
->set_metadata('description', $this->_template_title(lang('ebooks:of').' '.$name))
->set_metadata('keywords', $this->_template_title(lang('ebooks:of').' '.$name))
->set('genres', $genres)
->set('books', $books)
->set('genre', $genre)
->set('time', $time)
->set('pagination', $pagination)
->build('genres-list');
}
else
{
$this->template->title($this->_template_title(lang('ebooks:genres_by')))
->set_metadata('description', $this->_template_title(lang('ebooks:genres_by')))
->set_metadata('keywords', $this->_template_title(lang('ebooks:genres_by')))
->set('genres', $genres)
->build('genres-list');
}
}
And, this is the model:
public function count_genres_by($genre, $params)
{
return $this->db->select('*')
->from('downloads_books_book_info')
->join('keywords_applied', 'keywords_applied.hash = downloads_books_book_info.books_info_genre')
->join('keywords', 'keywords.id = keywords_applied.keyword_id')
->where('keywords.name', str_replace('-', ' ', $genre))
->where($params)
->count_all_results();
}
public function get_genres_by($genre, $params)
{
return $this->db->select('*')
->from('downloads_books_book_info')
->join('keywords_applied', 'keywords_applied.hash = downloads_books_book_info.books_info_genre')
->join('keywords', 'keywords.id = keywords_applied.keyword_id')
->where('keywords.name', str_replace('-', ' ', $genre))
->where($params)
->get()
->result();
}
As you can see in the first part of code, I got the time() four times, giving the delays:
18:49 - 19:03 - 19:41 - 19:41
I have a DB with about 5K entries. How can I optimize this code?
You can use 2.2.0-beta1 and take advantage of the Search system, which will store all keywords as text and knock out a few joins for your queries.
Otherwise you can build your own index table using blog events, which will store keywords next to blog id's.
The main problem is that your are running an SQL query on EVERY single returned item, whilst it would be quicker to work out all the keywords in one go. Even a SQL sub-query would be slightly quicker.
I have been using K2 Scroller module developed by Land of Coder. When I use this module to display same category items in the items view the module displays items in the ascending order of the date created and it is the default and only setting available in the module parameter settings in the back-end. However, I want the module to display the items in date wise descending order. So I chose to edit the default code in the helper which I suppose is used to process items based on the back-end settings. And this is the part of the code in the helper file which I think controls the order:
public function __getList( $params ){
global $mainframe;
/*some irrelevant code removed*/
$condition = $this->buildConditionQuery( $params );
$limitDescriptionBy = $params->get('limit_description_by','char');
$ordering = $params->get( 'k2_ordering', 'created_desc');
$limit = $params->get( 'limit_items', 5 );
$ordering = str_replace( '_', ' ', $ordering );
$my = &JFactory::getUser();
$aid = $my->get( 'aid', 0 );
/*some irrelevant code removed*/
$extraURL = $params->get('open_target')!='modalbox'?'':'&tmpl=component';
$excludeIds = $params->get('exclude_ids', '');
$db = &JFactory::getDBO();
$date =& JFactory::getDate();
$now = $date->toMySQL();
$dateFormat = $params->get('date_format', 'DATE_FORMAT_LC3');
$limitDescriptionBy = $params->get('limit_description_by','char');
$isAuthor= $params->get('itemAuthor',0);
require_once ( JPath::clean(JPATH_SITE.'/components/com_k2/helpers/route.php') );
$query = "SELECT a.*, cr.rating_sum/cr.rating_count as rating, c.name as categoryname,
c.id as categoryid, c.alias as categoryalias, c.params as categoryparams, cc.commentcount as commentcount".
" FROM #__k2_items as a".
" LEFT JOIN #__k2_categories c ON c.id = a.catid" .
" LEFT JOIN #__k2_rating as cr ON a.id = cr.itemid".
" LEFT JOIN (select cm.itemid as id, count(cm.id) as commentcount from #__k2_comments as cm
where cm.published=1 group by cm.itemid) as cc on a.id = cc.id";
$query .= " WHERE a.published = 1"
. " AND a.access get('featured_items_show','0') == 0 ){
$query.= " AND a.featured != 1";
} elseif( $params->get('featured_items_show','0') == 2 ) {
$query.= " AND a.featured = 1";
}
if( trim($excludeIds) ){
$query .= " AND a.id NOT IN(".$excludeIds.") ";
}
$query .= $condition . ' ORDER BY ' . $ordering;
$query .= $limit ? ' LIMIT ' . $limit : '';
$db->setQuery($query);
$data = $db->loadObjectlist();
/*some irrelevant code removed*/
return $data;
}
/**
* build condition query base parameter
*
* #param JParameter $params;
* #return string.
*/
public function buildConditionQuery( $params ){
$source = trim($params->get( 'k2_source', 'k2_category' ) );
if( $source == 'k2_category' ){
$catids = $params->get( 'k2_category','');
if( !$catids ){
return '';
}
$catids = !is_array($catids) ? $catids : '"'.implode('","',$catids).'"';
$condition = ' AND a.catid IN( '.$catids.' )';
} else {
$ids = preg_split('/,/',$params->get( 'k2_items_ids',''));
$tmp = array();
foreach( $ids as $id ){
$tmp[] = (int) trim($id);
}
$condition = " AND a.id IN('". implode( "','", $tmp ) ."')";
}
return $condition;
}
Am I editing the right part of the code or am I missing something else.
I am looking forward to your help
Thanks.
Maybe the best way would be to modify the xml file of the module.
I looked at the code of Lof K2Scroller (v 2.2 for Joomla 2.5) and the different ordering options are there.
However if you want to modify the default option, you are in the right file, just replace 'created_desc' for 'created_asc' .