There are many matching credentials inside the table which are inserted to an foreach loop however I am getting the results only from the first foreach element. How could I fix that?
foreach($matches as $match)
{
$object = $match->object;
$sales->whereRaw("match (`object`) against (?)", array($object));
if($match->colourBase == '1')
{
$sales->where('colour', '=', 'CC');
$sales->orWhere('colour', '=', 'CC+DD');
if($match->maxPrice)
{
$sales->where('price', '<=', $match->maxPrice);
}
if($match->minPrice)
{
$sales->where('price', '>=', $match->minPrice);
}
}
}
$results = $sales->orderBy('sales.updated_at', 'asc')->get();
#update
This is how I get $matches
$matches = Match::where('PeopleID', '=', $id)->get();
If you want only one record
use first() function.
No need to use foreach. :)
$matches = Match::where('PeopleID', '=', $id)->first();
Related
I have tried to trim "appointment" to check if it is equal to string that I have sent by trim function from ajax. But trim('appointment') doesn't give me what I need. How can delete whitespaces from object in sql to check some condition using where
public function category_filter(Request $request)
{
$appointment = json_decode($request->appointment);
$categories = [];
foreach($appointment as $a){
$cat_c_id = Products::where(trim('appointment'), '=', $a)->select('id')->get();
foreach($cat_c_id as $cat_c){
array_push($categories, $cat_c);
}
}
var_dump($categories);
}
The correct answer here is to fix your data and not store it with whitespace in the first place. Failing that, you need to use a raw statement:
public function category_filter(Request $request)
{
$appointment = json_decode($request->appointment);
$categories = [];
foreach($appointment as $a) {
$cat_c_id = Products::whereRaw('TRIM(appointment) = ?', [$a])
->select('id')
->get();
foreach($cat_c_id as $cat_c){
array_push($categories, $cat_c);
}
}
var_dump($categories);
}
Taking it a step further, you are performing pointless foreach loops that can be replaced with something like this:
public function category_filter(Request $request)
{
$appointment = json_decode($request->appointment);
// build a string like TRIM(appointment) IN (?,?,?,?)
$raw = 'TRIM(appointment) IN (' . implode(',', array_fill(0, count($appointment), '?')) . ')';
$categories = Products::whereRaw($raw, $appointment)
->select('id')
->get()
->toArray();
}
var_dump($categories);
}
trim('appointment') //this will trim the string 'appointment', not its value on table
try this (considering that Products::where allow this type of implementation):
...
$cat_c_id = Products::where('trim(appointment)', '=', trim($a))->select('id')->get();
...
I would apply a method for each element of an array to an object, how to achieve that ?
$array = ['state'=>'CA','name'=>'San Francisco']
//how to call ->where on each element to produce that ?
$documents = $this->reference
->where('state', '=', 'CA')
->where('name', '=', 'San Francisco');
->documents();
$query= $this->reference;
foreach($array as $field => $value) {
$query->where($field, '=', $value);
}
$documents = $query->documents();
The foreach syntax accepts a $k => $value pattern as its second parameter; for each element in the array, you execute the code in the foreach with $k being the current key of the array, and $v being its associated value.
It is the result function inside the HotelController.
public function result()
{
$data=Input::except(array('_token'));
$city= $data['city'];
$cities_id = DB::table('cities')
->select('id')
->where('cities.city_name', 'LIKE', "%$city%")
->get();
$hotel = array();
foreach ($cities_id as $value) {
$i=$value->id;
$hotel[] = DB::table('add_hotels')
->select('id')
->where('city_id', '=', $i)
->get();
}
var_dump($hotel);
exit();
return view('hotel.result',compact('hotel','city'));
}
This is the result which i'm getting, but I required only data marked by red color box
Try this query:
$cities_id = DB::table('cities')
->where('cities.city_name', 'LIKE', "%$city%")
->Join('add_hotels','add_hotels.city_id','=','cities.id')
->select('add_hotels.id')
->get();
var_dump($cities_id);
I'm currently trying to implement a search in my db for keywords. Therefore I split a string seperated by a comma, so I get an array containing a variable number of elements (one keyword).
I know that I can use a eloquent construct like that:
$products = Product::where([['keywords', 'LIKE', %samsung%], [keywords, 'LIKE', 's7']])->paginate(15);
to find a product with the keywords samsung,galaxy,s7.
Now I need this thing but automatically generated for a variable number of search query parts, so for every keyword in the array I need to add one ['keywords', 'LIKE', '...']...
How can I do this with Laravels Eloquent?
Use closure. First, make sure you stored list of keywords into array or the like. Then ...
$keywords = ['samsung', 's7', 'what else'];
$products = Product::where(function ($query) use ($keywords) {
foreach ($keywords as $keyword) {
$query->orWhere('keyword', 'like', $keyword);
}
})->paginate(15);
other example
$keywords = [
['name', 'LIKE', $searchQuery],
['category_id', '=', $selectedSubcategory],
];
$products = Product::where(function ($query) use ($keywords) {
foreach ($keywords as $keyword) {
$query->where($keyword);
}
})->paginate(15);
other than other
$keywords = [
['name', 'LIKE', $searchQuery],
['category_id', '=', $selectedSubcategory],
['please_id', '=', $learnPhpArray],
];
$products = Product::query();
foreach ($keywords as $keyword) {
$products = $products->where($keyword);
}
return $products->paginate(15);
What does the orWhere do? Does it connect the query parts with a AND?
No, with OR. As the inverse(?) the where itself does AND by default.
References
https://laravel.com/api/5.2/Illuminate/Database/Eloquent/Builder.html#method_where
https://laravel.com/api/5.2/Illuminate/Database/Eloquent/Builder.html#method_orWhere
Isn't it just to generate the array? Or am I misunderstanding the question?
<?php
$keys = ['samsung', 'lg', 'sony', 'nokia', 'apple'];
$keywords = [];
foreach($keys as $key){
$keywords[] = ['keywords', 'LIKE', '%'.$key.'%'];
}
$products = Product::where($keywords)->paginate(15);
You can do this:
$query = "Samsung galaxy S7"; // Or whatever the query is
$words = preg_split("/[ ,.]/",$query); //Split on space comma or dot. Maybe need more?
$queries = array_map(function ($word) {
return [ "keywords", "LIKE", "%$word%" ];
}, $words); //Transform single words to array of queries
$products = Product::where($queries)->paginate(15);
Check how the first part of the code works at: https://eval.in/730772
laravel 5.6
$keyWords = KeyWordModel::all();
$keyWordQuerys = [];
foreach ($keyWords as $key => $item) {
$keyWordQuerys[$key] = ['title', 'like', '%'.$item->name.'%'];
}
$contents = ContentModel::query();
foreach ($keyWordQuerys as $key => $item) {
$contents = $contents->orwhere([$item]);
}
$contents = $contents->orderBy('pubDate', 'DESC')->get();
I write code like this
$category = Input::get('category'); // ?category=1
if(!empty($category)){ // ?category=1, category=2
$lists = \App\Test::where('created_at', '<=', 'now()')
->where('category', $category) // append this.
->orderBy('id','desc')
->get();
}
else { // ?category=, category=0
$lists = \App\Test::where('created_at', '<=', 'now()')
->orderBy('id','desc')
->get();
}
That is so work but I think dirty code.
I dont wanna write same code again if I can.
So I wish to do like this ( Not working )
$category = Input::get('category'); // ?category=1
$lists = \App\Test::where('created_at', '<=', 'now()');
if(!empty($category)){ // ?category=1, category=2
$lists .= $lists::where('category', $category);
}
$lists .= $lists::orderBy('id','desc')->get();
Anyone know kind solutions?
Use this code
$lists = \App\Test::where('created_at', '<=', 'now()');
if(!empty($category)){ // ?category=1, category=2
$lists = $lists->where('category', $category);
}
$lists->orderBy('id','desc')->get();
You can do it like:
$lists = \App\Test::where('created_at', '<=', 'now()');
and then when you want to append anything, add it like this:
if(!empty($category)){ // ?category=1, category=2
$lists = $lists::where('category','=', $category);
}
you don't need to use .