$konten = Konten::all()->where('kategori','Announcement' AND 'kategori','Activities')->sortByDesc('id');
It's not work what is the right query for using AND Logic in query sir ? im so sorry i don't have much knowledge to find out the way.. the point is i want $konten contains the row from Konten where the kategori is Announcement and Activities.. how to make it happen ? it just showing konten where the kategori is activities the announcement not passed..
You can chain several where to achieve AND:
$konten = Konten::where('kategori', 'Announcement')
->where('kategori', 'Activities')
->orderBy('id', 'desc')
->get();
Or use whereIn like this:
$konten = Konten::whereIn('kategori', ['Announcement', 'Activities'])
->orderBy('id', 'desc')
->get();
To achieve an AND in Laravel, you simply chain ->where() calls:
$konten = Konten::where('kategori','Announcement')->where('kategori','Activities') ...
As a side note, Konten::all() returns a Collection, and is no longer database logic. You shouldn't call ::all() unless you specifically need every record in the database.
Refactor to the following:
$konten = Konten::where('kategori','Announcement')
->where('kategori','Activities')
->orderBy('id', 'desc')
->get();
This will leverage the database to perform the filtering/ordering, instead of offloading every record into a Collection and allowing PHP to perform the same logic, which can be incredibly inefficient depending on the number of records.
try this:
$konten = Konten::whereIn('kategori', ['Announcement', 'Activities'])->orderBy('id', 'desc')->get();
I have a strong feeling that you probably seek for 'orWhere' clause... If you want ALL records when kategori column equals 'Announcement' and all records when kategori equals 'Activities' you sholud use orWhere clause like so:
$konten = Konten::where('kategori', 'Announcement')
->orWhere('kategori', 'Activities')
->orderBy('id', 'desc')
->get();
Or as mentioned in answers below you can use whereIn statement.
Related
Code
$result = DB::table('disaster_rescue_data')
->join('users', 'disaster_rescue_data.username', '=', 'users.email')
->get();
Problem
I have this very simple join as mentioned in the above code. However when I render the data on a view or dd the $result, I get the same row duplicated and I can not figure out why. (The rows contain the same data.)
(I am using Laravel 5.4)
Can someone please help me figure out why? (I tried different techniques and none of them worked! Thanks.)
to prevent duplication, you should use distinct() method, this method Returns only unique items from the result.
in order to do that, first you must stricly select what you want:
$result = DB::table('disaster_rescue_data')
->select('disaster_rescue_data.*')
->join('users', 'disaster_rescue_data.username', '=', 'users.email')
->distinct()->get();
You could try using distinct in the query. Distinct removes duplicates in a result set.
For example
$result = DB::table('disaster_rescue_data')
->distinct()
->join('users', 'disaster_rescue_data.username', '=', 'users.email')
->get();
See https://laravel.com/docs/5.4/queries
EDIT:
Ok, I am thinking you can now use groupBy to get the unique results. Although it's not clear what your data structure is so this is a guess to use "users.email". Maybe it could be "disaster_rescue_data.username" to group by. Experiment and see.
$result = DB::table('disaster_rescue_data')
->distinct()
->join('users', 'disaster_rescue_data.username', '=', 'users.email')
->groupBy('users.email')
->get();
SELECT * FROM user_fields WHERE (SELECT CITY FROM register_expert WHERE PERMISSION=1 AND ID=user_fields.ID_USER_FIELD)='$city_save'AND TITLE_USER_FIELD='$text_search_service';
Here is register_expert table image
And here is user_fields table mage
Assuuming,
userFields is your models.
userFields::selectRaw("user_fields.ID_USER_FIELD")
->join('register_expert', function($join) use ($city_save){
$join->on('register_expert.id', 'user_fields.ID_USER_FIELD')
->where('PERMISSION', '1')
->where('city', $city_save)
})->where('TITLE_USER_FIELD', $text_search_service);
Try this code.
I think the Eloquent query should look something like this but as I said in my comment the database and query is not well designed so I don't think it will work but just so you have an idea of how to make more complex queries in Eloquent.
$registerExperts = RegisterExperts::whereColumn('ID_USER_FIELD', 'user_fields.ID')
->Andwhere('PERMISSION', '=', 1)
->limit(1)
->select('city')
->get();
$users = User::where($registerExperts->get('city') , '=', $city_save)
->andWhere('TITLE_USER_FIELD', '=', $text_search_service)
->get();
And here's a good first article to see how to make complex queries using Eloquent ORM : Dynamic relationships in Laravel using subqueries by Jonathan Reinink
I need sorting the Records data according to Relationship.
I am trying below Query.
$data = Lead::with('bdm', 'status_code', 'bdm.bdm')->get()->sortByDesc('bdm.bdm.name');
It works fine but I need data with pagination which is giving by Laravel 5 by default.
So If I am trying with below query . It is giving error.
$data = Lead::with('bdm', 'status_code', 'bdm.bdm')->pagination(20)->sortByDesc('bdm.bdm.name');
I am trying an other way to do the same task. It works fine but it is not sorting the records.
$data = Lead::with(['bdm','status_code', 'bdm.bdm' => function ($query) {
$query->orderBy('name', 'desc');
}])->paginate(20);
So kindly can anyone give me solution how to adjust this query.
Any Help will be appreciated.
Thanks
You should be using a join statement to do that.
If I were to assume your column names it should look something like this:
$data = Lead::with(['status_code', 'bdm.bdm'])
->join('bdms', 'bdms.id', '=', 'leads.bdm_id')
->orderBy('bdms.name', 'desc')
->paginate(20);
And the first bdm parameter in your query is redundant. It will be handled during bdm.bdm anyway.
If I do this:
return $this->roles()->detach($role);
all roles are removed.
How to limit that to only the last one?
You can do it without timestamps:
$lastRole = $user->roles()
->orderBy( $user->roles()->getTable() .'id', 'desc')
->first();
$user->roles()->detach($lastRole);
or with timestamps:
$lastRole = $user->roles()->latest()->first();
$user->roles()->detach($lastRole);
you may try this, I did not test it:
return $this->roles()->orderBy('id', 'desc')->first()->detach($role);
You can also order by timestamps, if no primary id is present, like this:
return $this->roles()->orderBy('created_at', 'desc')->first()->detach($role);
for this to work, you also have to edit your model, from the docs:
If you want your pivot table to have automatically maintained
created_at and updated_at timestamps, use the withTimestamps method on
the relationship definition:
return $this->belongsToMany('Role')->withTimestamps();
Another thing would be not to use model at all, because looking at this issue #3585 it is not that easy. Taylor closed it without a comment, so I assume it not get implemented. The solution should be (assuming you have timestamps columns migrated in the table). Tested code:
$last = DB::table($user->roles()->getTable())
->orderBy('created_at', 'desc')
->first();
DB::table($user->roles()->getTable())
->where('created_at', '=', $last->created_at)
->delete();
I'm stuck on a simple task.
I just need to order results coming from this call
$results = Project::all();
Where Project is a model. I've tried this
$results = Project::all()->orderBy("name");
But it didn't work. Which is the better way to obtain all data from a table and get them ordered?
You can actually do this within the query.
$results = Project::orderBy('name')->get();
This will return all results with the proper order.
You could still use sortBy (at the collection level) instead of orderBy (at the query level) if you still want to use all() since it returns a collection of objects.
Ascending Order
$results = Project::all()->sortBy("name");
Descending Order
$results = Project::all()->sortByDesc("name");
Check out the documentation about Collections for more details.
https://laravel.com/docs/5.1/collections
In addition, just to buttress the former answers, it could be sorted as well either in descending desc or ascending asc orders by adding either as the second parameter.
$results = Project::orderBy('created_at', 'desc')->get();
DO THIS:
$results = Project::orderBy('name')->get();
Why?
Because it's fast! The ordering is done in the database.
DON'T DO THIS:
$results = Project::all()->sortBy('name');
Why?
Because it's slow. First, the the rows are loaded from the database, then loaded into Laravel's Collection class, and finally, ordered in memory.
2017 update
Laravel 5.4 added orderByDesc() methods to query builder:
$results = Project::orderByDesc('name')->get();
While you need result for date as desc
$results = Project::latest('created_at')->get();
In Laravel Eloquent you have to create like the query below it will get all the data from the DB, your query is not correct:
$results = Project::all()->orderBy("name");
You have to use it in this way:
$results = Project::orderBy('name')->get();
By default, your data is in ascending order, but you can also use orderBy in the following ways:
//---Ascending Order
$results = Project::orderBy('name', 'asc')->get();
//---Descending Order
$results = Project::orderBy('name', 'desc')->get();
Check out the sortBy method for Eloquent: http://laravel.com/docs/eloquent
Note, you can do:
$results = Project::select('name')->orderBy('name')->get();
This generate a query like:
"SELECT name FROM proyect ORDER BY 'name' ASC"
In some apps when the DB is not optimized and the query is more complex, and you need prevent generate a ORDER BY in the finish SQL, you can do:
$result = Project::select('name')->get();
$result = $result->sortBy('name');
$result = $result->values()->all();
Now is php who order the result.
You instruction require call to get, because is it bring the records and orderBy the catalog
$results = Project::orderBy('name')
->get();
Example:
$results = Result::where ('id', '>=', '20')
->orderBy('id', 'desc')
->get();
In the example the data is filtered by "where" and bring records greater than 20 and orderBy catalog by order from high to low.
Try this:
$categories = Category::all()->sortByDesc("created_at");
One interesting thing is multiple order by:
according to laravel docs:
DB::table('users')
->orderBy('priority', 'desc')
->orderBy('email', 'asc')
->get();
this means laravel will sort result based on priority attribute. when it's done, it will order result with same priority based on email internally.
EDIT:
As #HedayatullahSarwary said, it's recommended to prefer Eloquent over QueryBuilder. off course i didn't encourage using QueryBuilder and we all know that each has own usecases.
Any way so why i wrote an answer with QueryBuilder? As we see in eloquent documents:
You can think of each Eloquent model as a powerful query builder allowing you to fluently query the database table associated with the model.
BTWS the above code with eloquent should be something like this:
Project::orderBy('priority', 'desc')
->orderBy('email', 'asc')
->get();