Laravel 5 eloquent whereIn - php

Hope anybody can help me, I need to search for items that have category id = x in the database
Example table items
id,cats,name etc...
cats = '1,19' or maybe just '19' or maybe '1,9'
So for this example I need a to search for items that have cats with 9
I tried this but when I search for 9 it also shows 19
$items = Items::where(function($query)use($cat) {
$query->where('cats', 'like', '%,'.$cat->id.'%');
$query->orWhere('cats', 'like', '%'.$cat->id.',%');
$query->orWhere('cats', 'like', '%'.$cat->id.'%');
})->orderBy('updated_at', 'DSC')->get();
I also tried something
$items = Items::whereIn(explode(',', 'cats'), $cat->id)->get();
but it doesn't work
Appreciate any help to find the easiest and shorts way of doing this, regards

It's quite hard to understand what you want to achieve but I'll try. First of all as #particus mentioned the best way is to create pivot table when you don't need to worry about such things.
But the solution if you have list of ids in a columns separated by coma is not storing values like
1,2,3
but always adding , at the beginning and at the end, so it should be in this case:
,1,2,3,
This way, if you have in your table ,19,2,3, and you want to search for value 9, you should use look for ,9, string, for example:
$id = 9;
$items = Items::where('column', LIKE '%,'.$id.',%')->get();
Now for above string no record will be found, but if you have ,9,2,3, or just ,9, the desired record will be found.

Assuming you're using MySQL, you can use the FIND_IN_SET function.
$items = Items::whereRaw("FIND_IN_SET(".$cat->id.", cats)")->orderBy('updated_at', 'DESC')->get();
Please note, this will not use any indexes defined on the cats column. Storing array like data in a field is usually a big red flag. You would benefit by normalizing this out now, rather than trying to work around the current design.

Related

using count on comparing multiple row with different values in laravel 4.2

i have this table called dbo_modulesand it has columns ModuleCountLeft and ModuleCriticalLevel
in my controller, im trying to get the number of modules where ModuleCountLeft is less than the value of ModuleCriticalLevel. in my table, the values of ModuleCountLeft and ModuleCriticalLevel differs from row to row. so in my controller i uses this query:
$critical = DB::table('dbo_modules')
->where('ModuleCountLeft' , '<=' , DB::table('dbo_modules')->pluck('ModuleCriticalLevel') )
->count();
the problem here is that im not getting the correct values. It get the first ModuleCriticalLevel and makes it the point of comparison. for example the first ModuleCriticalLevel in the table is 20, it compares all the ModuleCountLeft to 20. Can anyone tell me what im doing wrong? or is my code wrong? please. Thanks in advance.
Try like following. You need not to pluck anything
$critical = DB::table('dbo_modules')
->where('ModuleCountLeft' ,'<=' ,'ModuleCriticalLevel')
->count();

Laravel: How to get last N entries from DB

I have table of dogs in my DB and I want to retrieve N latest added dogs.
Only way that I found is something like this:
Dogs:all()->where(time, <=, another_time);
Is there another way how to do it? For example something like this Dogs:latest(5);
Thank you very much for any help :)
You may try something like this:
$dogs = Dogs::orderBy('id', 'desc')->take(5)->get();
Use orderBy with Descending order and take the first n numbers of records.
Update (Since the latest method has been added):
$dogs = Dogs::latest()->take(5)->get();
My solution for cleanliness is:
Dogs::latest()->take(5)->get();
It's the same as other answers, just with using built-in methods to handle common practices.
Dogs::orderBy('created_at','desc')->take(5)->get();
You can pass a negative integer n to take the last n elements.
Dogs::all()->take(-5)
This is good because you don't use orderBy which is bad when you have a big table.
You may also try like this:
$recentPost = Article::orderBy('id', 'desc')->limit(5)->get();
It's working fine for me in Laravel 5.6
I use it this way, as I find it cleaner:
$covidUpdate = COVIDUpdate::latest()->take(25)->get();
Ive come up with a solution that helps me achieve the same result using the array_slice() method. In my code I did array_slice( PickupResults::where('playerID', $this->getPlayerID())->get()->toArray(), -5 ); with -5 I wanted the last 5 results of the query.
The Alpha's solution is very elegant, however sometimes you need to re-sort (ascending order) the results in the database using SQL (to avoid in-memory sorting at the collection level), and an SQL subquery is a good way to achieve this.
It would be nice if Laravel was smart enough to recognise we want to create a subquery if we use the following ideal code...
$dogs = Dogs::orderByDesc('id')->take(5)->orderBy('id')->get();
...but this gets compiled to a single SQL query with conflicting ORDER BY clauses instead of the subquery that is required in this situation.
Creating a subquery in Laravel is unfortunately not simply as easy as the following pseudo-code that would be really nice to use...
$dogs = DB::subQuery(
Dogs::orderByDesc('id')->take(5)
)->orderBy('id');
...but the same result can be achieved using the following code:
$dogs = DB::table('id')->select('*')->fromSub(
Dogs::orderByDesc('id')->take(5)->toBase(),
'sq'
)->orderBy('id');
This generates the required SELECT * FROM (...) AS sq ... sql subquery construct, and the code is reasonably clean in terms of readability.)
Take particular note of the use of the ->toBase() function - which is required because fromSub() doesn't like to work with Eloquent model Eloquent\Builder instances, but seems to require a Query\Builder instance). (See: https://github.com/laravel/framework/issues/35631)
I hope this helps someone else, since I just spent a couple of hours researching how to achieve this myself. (I had a complex SQL query builder expression that needed to be limited to the last few rows in certain situations).
For getting last entry from DB
$variable= Model::orderBy('id', 'DESC')->limit(1)->get();
Imagine a situation where you want to get the latest record of data from the request header that was just inserted into the database:
$noOfFilesUploaded = count( $request->pic );// e.g 4
$model = new Model;
$model->latest()->take($noOfFilesUploaded);
This way your take() helper function gets the number of array data that was just sent via the request.
You can get only ids like so:
$model->latest()->take($noOfFilesUploaded)->puck('id')
use DB;
$dogs = DB::select(DB::raw("SELECT * FROM (SELECT * FROM dogs ORDER BY id DESC LIMIT 10) Var1 ORDER BY id ASC"));
Dogs::latest()->take(1)->first();
this code return the latest record in the collection
Can use this latest():
$dogs = Dogs::latest()->take(5)->get();

How to write a dynamic SQL query in PHP?

Hello fellow StackOverflowers,
As modifications on my website were needed in result of massive growth and suggestions from the public, I needed to modify my database, which I have already done to adjust it to the visitor suggestions. Right, very confusing so I'll just get to the point:
Current query:
$arow=mysql_fetch_assoc(mysql_query("SELECT * FROM animelist WHERE id = '".$_REQUEST['id']."'"));
$placeholders = array(' ', ',', ':');
$replacements = array('-', '', '');
$title=str_replace($placeholders, $replacements,$arow['name']);
$title=preg_replace("/[^a-zA-Z0-9\s-]/", "", $title);
$link=$title."-".$arow['id'];
$link="Stream-".$title."-Episode-".$row1['episodes_id']."-".$row1['language']."-".$row1['id'];
Initially the part -Episode- was only needed to be named/written as '-Episode-', however to user suggestions and I completely agree, it needs to be dynamic aswell. Lets say (using the terms for reference only) at first the website only had Episodes and not Movies, but now also has Movies. So we want this part to be dynamic aswell. For this we use database information, I have made a column 'type' INT(1) in the table 'items' I suggest 0 to be -Episode- and if value under type is 1 then I suggest it to be -Movie-.
Now the question is how do I correctly implement it in the query? I understand more queries need to be made similar to the one from $title or $row1. this is what I have so far, but it is not complete yet, because I don't know how to:
$link="Stream-".$title."-.$type.-".$row1['episodes_id']."-".$row1['language']."-".$row1['id'];
$type=$arow['type']
Now there should be a code, which I am not sure of how to write correctly, which makes the condition that if type = 0 then echo Episode, elseif type = 1 then echo Movie.
I greatly appreciate the time you took to read this through and hope you can help me out.
Edit:
Assume $row1, is fetched from table named 'videos' and not from 'animelist', however the table 'videos' each video has an 'id' but also has an column named 'anime_id', this anime_id is equal to the 'id' in 'animelist', in short videos id is the post, and anime_id is the category.
More queries need to be written now to balance the game, please help me out, I am stuck.
Thanks in advance,
Inder
$type = ($arow['type']==0) ? "Episode" : "Movie";
or
$type = $arow['type'] ? "Episode" : "Movie";

Kohana orm order asc/desc?

I heed two variables storing the maximum id from a table, and the minimum id from the same table.
the first id is easy to be taken ,using find() and a query like
$first = Model::factory('product')->sale($sale_id)->find();
but how can i retrieve the last id? is there a sorting option in the Kohana 3 ORM?
thanks!
Yes, you can sort resulting rows in ORM with order_by($column, $order). For example, ->order_by('id', 'ASC').
Use QBuilder to get a specific values:
public function get_minmax()
{
return DB::select(array('MAX("id")', 'max_id'),array('MIN("id")', 'min_id'))
->from($this->_table_name)
->execute($this->_db);
}
The problem could actually be that you are setting order_by after find_all. You should put it before. People do tend to put it last.
This way it works.
$smthn = ORM::factory('smthn')
->where('something', '=', something)
->order_by('id', 'desc')
->find_all();
Doing like this, I suppose you'll be :
selecting all lines of your table that correspond to your condition
fetching all those lines from MySQL to PHP
to, finally, only work with one of those lines
Ideally, you should be doing an SQL query that uses the MAX() or the MIN() function -- a bit like this :
select max(your_column) as max_value
from your_table
where ...
Not sure how to do that with Kohana, but this topic on its forum looks interesting.

How do I write a search query using Kohana PHP?

I have a table (product_shoppingcart) with 4 columns :
id, product_id, shoppingcart_id, product_quantity.
I'm using Kohana's ORM.
I want to write a search query which returns all the rows where the shoppingcart_id column contains 1 (for example).
I already tried:
$arr = ORM::factory('product_shoppingcart')->where('shoppingcart_id',$shoppingcartID)->find_all();
but that doesn't work.
Can anyone please help me out?
Your example code should work, but perhaps the problem is that you're not iterating over your result set?
$results = ORM::factory('product_shoppingcart')
->where('shoppingcart_id', $shoppingcartID)
->find_all();
foreach ($results as $product_shoppingcart) {
print Kohana::debug($product_shoppingcart->as_array());
}
If you have more than one row with that id, this should give you a result iterator in $results, which you then walk with the foreach loop. I have lots of examples of similar working code, if you're still not able to get it working.
Here is what it would look like:
$arr = ORM::factory('product_shoppingcart')->where(
'shoppingcart_id',"=",$shoppingcartID)->find_all();
Shouldnt your table be "product_shoppingcarts" or am I missing something?

Categories