Paginate in relationship and order by - php

I have List. List has many posts.
I want to get all post of some lists, sort posts and paginate it.
I try this:
$list = List::whereId('1')->firstOrFail();
$posts = $feed->posts()->orderBy('id')->paginate(Request::input('per_page'))->appends(Request::input());
return compact('list','posts');
Now I can get List and paginate posts, but ordeBy doesn't work?
How order it? Or any other way to solve this problem?

$posts= Post::orderBy('id','desc');

It works and sorts by ASC by default. If you want to reverse it, use DESC:
->orderBy('id', 'desc')
Or:
->latest('id')

->orderBy('id','asc') for Ascending
->orderBy('id','desc') for Decending

Related

How to get data with sorting from controller?

I have the following query. I want to get data from the database sorted alphabetically:
$states = State::where('status', 1)->sortBy('name')->get();
Which framework are you using
If laravel then write below syntax
$states = State::where('status', 1)->orderBy('name', 'ASC')->get();
You need to use order by SQL keywords to get it alphabetically ordered data as ascending or descending order. For laravel use check Ordering, Grouping, Limit, & Offset from laravel docs.
For your use case it is simple as
$states = State::where('status', 1)->orderBy('name', 'ASC')->get();
for ascending order

How to achieve sub collection on a collection of an array?

I want to get the detailed product of a collection from groupBy in laravel. How can I achieve that?
I'm using php 7.1 and Laravel. I can get the collection for the total report for year, month, and day.
But can I get detailed product of that collection ?
My query for getting the collection in the controller
$totalBelanjaTahun = DB::table('assets')
->select(DB::raw('EXTRACT(MONTH FROM belitanggal_assets) AS monthCoba, SUM(beliharga_assets) AS harga_beli'))
->where('belitanggal_assets', 'like', '%'.$tahun.'%')
->groupBy(DB::raw('monthCoba'))
->get();
return view('DilarangBuka.reportTotalBelanjaTahun', compact('totalBelanjaTahun', 'tahun', 'totalPertahun'));
How can I achieve get detailed of product of that array, not just get the date and the price? Thanks
Don't groupBy records in mysql, you will get first record of every groups.
Try to get them out.
$totalBelanjaTahun = DB::table('assets')
->select(DB::raw('EXTRACT(MONTH FROM belitanggal_assets) AS monthCoba, beliharga_assets AS harga_beli, field1, field2, field3'))
->where('belitanggal_assets', 'like', '%'.$tahun.'%')
->get();
And groups them by collect
collect($totalBelanjaTahun)->groupBy('monthCoba')
Hope this can help you.

Prevent getting a duppicate data from the database in CodeIgniter

I'm trying to get data from the database filtered by some categories
This is my code in CodeIgniter
$this->db
->select('*')
->from($this->table)
->join('sites','sites.id = categories_by_site.site_id')
->where('categories_by_site.category_id', $categories[0])
->or_where('categories_by_site.category_id', $categories[1])
->order_by('id', 'ASC')
->get()
->result();
I simplify my code for the sake of this question, the above query take the categories as a search filter and used it to get result from the database.
There can be many categories filter to search at the same time, that's why I am using or_where() method.
The problem with this, when I got the result data, it has duplicate row of entries in object array.
Anyone can suggest how to prevent from getting a duppicate data from the database using above query?
Thanks
You can use group_by to solve this issue
Replace your code with
$this->db
->select('*')
->from($this->table)
->join('sites','sites.id = categories_by_site.site_id')
->where('categories_by_site.category_id', $categories[0])
->or_where('categories_by_site.category_id', $categories[1])
->order_by('id', 'ASC')
->group_by('categories_by_site.category_id')
->get()
->result();
You can eleminate duplicate values using distinct or group by
As you select all fields a group by is better in my opinion. Example to group by category_id
$this->db->group_by('category_id');

Get Count in mysql query in laravel

I wants to select the count of votes got for each items.Following query works fine but there is a problem if there is no vote for an item then that item is not showing in result.I actually wants details of each items and votes.If there is no vote for an item it should be shown count zero.
How can i achieve it?
DB::table('wonders')
->leftjoin('vote','votes.wonderId','=','wonders.id')
->select('wonders.id','wonders.title',DB::raw('count(votes.vote) as votes'))
->get();
Try this
DB::table('wonders')
->leftjoin('vote','votes.wonderId','=','wonders.id')
->select('wonders.id','wonders.title',DB::raw('ifnull(count(votes.vote),0) as votes'))
->groupBy('wonders.id')
->get();
maybe you need to use iffnull,try this
DB::table('wonders')
->leftjoin('vote','votes.wonderId','=','wonders.id')
->select('wonders.id','wonders.title',DB::raw('ifnull(count(votes.vote),0) as votes'))
->get();
Try this
DB::table('wonders')
->leftjoin('vote','votes.wonderId','=','wonders.id')
->selectRaw('wonders.id','wonders.title',count(votes.vote) as votes)
->groupBy('wonders.id')
->get();

Order by multiple columns with Doctrine

I need to order data by two columns (when the rows have different values for column number 1, order by it; otherwise, order by column number 2)
I'm using a QueryBuilder to create the query.
If I call the orderBy method a second time, it replaces any previously specified orderings.
I can pass two columns as the first parameter:
->orderBy('r.firstColumn, r.secondColumn', 'DESC');
But I cannot pass two ordering directions for the second parameter, so when I execute this query the first column is ordered in an ascending direction and the second one, descending. I would like to use descending for both of them.
Is there a way to do this using QueryBuilder? Do I need to use DQL?
You have to add the order direction right after the column name:
$qb->orderBy('column1 ASC, column2 DESC');
As you have noted, multiple calls to orderBy do not stack, but you can make multiple calls to addOrderBy:
$qb->addOrderBy('column1', 'ASC')
->addOrderBy('column2', 'DESC');
In Doctrine 2.x you can't pass multiple order by using doctrine 'orderBy' or 'addOrderBy' as above examples. Because, it automatically adds the 'ASC' at the end of the last column name when you left the second parameter blank, such as in the 'orderBy' function.
For an example ->orderBy('a.fist_name ASC, a.last_name ASC') will output SQL something like this 'ORDER BY first_name ASC, last_name ASC ASC'. So this is SQL syntax error. Simply because default of the orderBy or addOrderBy is 'ASC'.
To add multiple order by's you need to use 'add' function. And it will be like this.
->add('orderBy','first_name ASC, last_name ASC'). This will give you the correctly formatted SQL.
More info on add() function. https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/query-builder.html#low-level-api
Hope this helps. Cheers!
you can use ->addOrderBy($sort, $order)
Add:Doctrine Querybuilder btw. often uses "special" modifications of the normal methods, see select-addSelect, where-andWhere-orWhere, groupBy-addgroupBy...
You can use orderBy() followed by an addOrderBy() - nesting several orderBy()'s is not possible, but nesting several addOrderBy()'s also works after the initial orderBy().
Example:
$this->createQueryBuilder('entity')
->orderBy('entity.addDate', 'DESC')
->addOrderBy('entity.id', 'DESC')
The orderBy method requires either two strings or an Expr\OrderBy object. If you want to add multiple order declarations, the correct thing is to use addOrderBy method, or instantiate an OrderBy object and populate it accordingly:
# Inside a Repository method:
$myResults = $this->createQueryBuilder('a')
->addOrderBy('a.column1', 'ASC')
->addOrderBy('a.column2', 'ASC')
->addOrderBy('a.column3', 'DESC')
;
# Or, using a OrderBy object:
$orderBy = new OrderBy('a.column1', 'ASC');
$orderBy->add('a.column2', 'ASC');
$orderBy->add('a.column3', 'DESC');
$myResults = $this->createQueryBuilder('a')
->orderBy($orderBy)
;
The comment for orderBy source code notes: Keys are field and values are the order, being either ASC or DESC.. So you can do orderBy->(['field' => Criteria::ASC]).

Categories