I have searchDetails array in my search. I have done all other search and get data on filter, Problem is that when i search with stone_min, stone_max I get data if there is only one searchDetails array, if there is two data it is return null. How can i do this ? I want search with stone_min, stone_max for particular product_id.
what i try :
Example for data to search :
{
"limit": 1000,
"offset":0,
"user_id": "",
"min_price": "",
"max_price": "",
"searchDetails": [
{
"product_id": "1",
"attributeId": [],
"is_exclude": "no",
"stone_min": "5",
"stone_max": "15"
},
{
"product_id": "2",
"attributeId": [],
"is_exclude": "no",
"stone_min": "100",
"stone_max": "500"
}
]
}
My query for getting all data
$searchablePost = Post::with(['product','postattribute.attribute.category','user.userDetails'])
->whereIn('product_id', $userApprovalProductIDs)
->where('status', 'Active')
->whereIn('demand_or_supply', $demand_or_supply);
Search for min-max stone :
if (count($searchDetails) > 0) {
$j = 0;
foreach ($searchDetails as $value) {
if (strtolower(trim($value['is_exclude'])) == "no") {
$searchablePost = $searchablePost->where(function ($query) use ($value) {
if ($value['stone_min'] && $value['stone_max']) {
if (isset($j) && $j == 0){
$query->where('stone_min', '>=', $value['stone_min'])->where('stone_max', '<=', $value['stone_max'])->where("product_id", (int)$value['product_id']);
} else {
$query->where('stone_min', '>=', $value['stone_min'])->where('stone_max', '<=', $value['stone_max'])->where("product_id", (int)$value['product_id']);
}
}
});
}
}
}
$searchedPost = $searchablePost->offset($offset)->limit($limit)->orderBy('id','desc')->get();
If you want to search between stone_min and stone_max for particualar product then do:
$request = json_decode($request->searchDetails, true);
$stoneMinMax = collect($request)->pluck('stone_min', 'stone_max');
Product::where(function($q) use($productId) ($stoneMinMax){
$q->where('product_id', $productId)
->whereBetween('stone_column', $stoneMinMax->toArray());
})->get();
Related
This is my query to get the product name and total quantity sold.
$prd = DB::table('order_details')
->join('products', 'order_details.product_id', '=', 'products.id')
->select('products.name', DB::raw('SUM(quantity) as quantity'))
->groupBy('products.name')
->orderBy('quantity', 'desc')
->get();
return $prd;
This is the output.
[
{
"name": "PINK",
"quantity": "22"
},
{
"name": "WHITE",
"quantity": "14"
},
{
"name": "RED",
"quantity": "13"
}
]
But I need it to be in this format. For it to work with chartjs.
{
"PINK": 22,
"WHITE": 14,
"RED": 13
}
This is what I've so far. I tried to use collection map. But I'm not sure how to return the quantity portion. Any pointers?
return $prd->groupBy('name')->map(function ($item, $key) {
return ''; // what should I return here to get the qty?
});
Current half baked output
{
"PINK": "",
"WHITE": "",
"RED": "",
}
You can use pluck() instead of get() for this:
$prd = DB::table('order_details')
->join('products', 'order_details.product_id', '=', 'products.id')
->select('products.name', DB::raw('SUM(quantity) as quantity'))
->groupBy('products.name')
->orderBy('quantity', 'desc')
->pluck('name', 'quantity');
I have some JSON data which get from an API. I need only the products name from there. How can I get this? I am already trying with foreach loop but I can't. I am using laravel framework version 6.0
[
{
"id": 2,
"name": "Bijj",
"categories": [
{
"id": 10,
"name": "Rice",
"sbu": 2,
"products" : [
{
"id": 25,
"name": "Rajkumar",
"skus": [],
"short_description": "বাংলাদেশের আবহাওয়া উপযোগী হাইব্রিড ধান",
},
{
"id": 50,
"name": "Sera",
"skus": [],
"short_description": "বাংলাদেশের আবহাওয়া উপযোগী হাইব্রিড ধান",
}
]
},
{
"id": 20,
"name": "Vhutta",
"sbu": 2,
"products" : [
{
"id": 129,
"name": "Pack-139",
"skus": [],
"short_description": "মোচায় ৮৬ % দানা ও ১৪ % শাঁস",
},
{
"id": 125,
"name": "Don-12",
"skus": [],
"short_description": "সারা বৎসর চাষ উপযোগী",
}
]
}
]
}
]
I want to get only the all products name form there.
$getSbu = Helper::CreateGuzzleHttpClient('sbu');
foreach ($getSbu as $value) {
if($value->id == 2) {
foreach ($value->categories as $category) {
$products = $category->products;
}
}
}
After decode you can simply use this helper
use Illuminate\Support\Arr;
Arr::only($array, ['categories.products.name']);
or
Arr::only($array, ['categories.*.name']);
you want get only product's name ??
and if your data array then you have to change $value['id']
$product_names = [];
foreach ($getSbu as $value) {
if($value->id == 2) {
foreach ($value->categories as $category) {
foreach ($category->products as $product) {
$product_names[] = $product->name;
}
}
}
}
dd($product_names);
foreach (json_decode($getSbu) as $value) {
Foreach works in an array so first you must decode it in order to parse it as an array.
Since you use object parsing you don't have to use parameter true in your json_decode function. If you want an array instead of an object you can use:
foreach (json_decode($getSbu,true) as $value) {
but then you access your value like array fields, for example value['id']
Your code should look like:
$getSbu = Helper::CreateGuzzleHttpClient('sbu');
foreach (json_decode($getSbu) as $value) {
if($value->id == 2) {
foreach ($value->categories as $category) {
$products = $category->products;
}
}
}
Leverage aravel collections
// this is just ur data but as json string
$var = '[{"id":2,"name":"Bijj","categories":[{"id":10,"name":"Rice","sbu":2,"products":[{"id":25,"name":"Rajkumar","skus":[],"short_description":"বাংলাদেশের আবহাওয়া উপযোগী হাইব্রিড ধান"},{"id":50,"name":"Sera","skus":[],"short_description":"বাংলাদেশের আবহাওয়া উপযোগী হাইব্রিড ধান"}]},{"id":20,"name":"Vhutta","sbu":2,"products":[{"id":129,"name":"Pack-139","skus":[],"short_description":"মোচায় ৮৬ % দানা ও ১৪ % শাঁস"},{"id":125,"name":"Don-12","skus":[],"short_description":"সারা বৎসর চাষ উপযোগী"}]}]}]';
$objCollection = collect(json_decode($var, true));
$productNames = $objCollection->pluck('categories.*.products.*.name');
dd($productNames);
I'm new to Laravel and I'm trying to build a query.
I want to add multiple where by condititions, but I can't achieve it.
If I do it, it works:
$query = Frete::all();
//or
$query = Frete::where('estado_destino_id', '=', $request->destino);
But, what I want is to set multiple where based on some conditions, something like this:
public function fretes(Request $request){
$query = Frete::all();
if ($request->destino){
$query->where('estado_destino_id', '=', $request->destino);
}
if ($request->veiculo){
$query->where('veiculo_id', '=', $request->veiculo);
}
$query->get();
return response()->json($query);
}
The above code returns all table and it is ignoring wheres.
I also tried this $query = DB::table('fretes'); instead of $query = Frete::all();
This way, JSON returned is:
{
"connection": {},
"grammar": {},
"processor": {},
"bindings": {
"select": [],
"from": [],
"join": [],
"where": [
1
],
"having": [],
"order": [],
"union": []
},
"aggregate": null,
"columns": null,
"distinct": false,
"from": "fretes",
"joins": null,
"wheres": [
{
"type": "Basic",
"column": "estado_destino_id",
"operator": "=",
"value": 1,
"boolean": "and"
}
],
"groups": null,
"havings": null,
"orders": null,
"limit": null,
"offset": null,
"unions": null,
"unionLimit": null,
"unionOffset": null,
"unionOrders": null,
"lock": null,
"operators": [
"=",
"<",
">",
"<=",
">=",
"<>",
"!=",
"<=>",
"like",
"like binary",
"not like",
"ilike",
"&",
"|",
"^",
"<<",
">>",
"rlike",
"regexp",
"not regexp",
"~",
"~*",
"!~",
"!~*",
"similar to",
"not similar to",
"not ilike",
"~~*",
"!~~*"
],
"useWritePdo": false
}
I've seen many posts and I've tried to implement it without success.
The all() method doesn't return a query. It executes SELECT * FROM table and returns the results. You need to start a new query then add the conditions to it Frete::query();
public function fretes(Request $request){
$query = Frete::query();
if ($request->destino){
$query->where('estado_destino_id', '=', $request->destino);
}
if ($request->veiculo){
$query->where('veiculo_id', '=', $request->veiculo);
}
$results = $query->get();
return response()->json($results);
}
use here conditional-clauses
public function fretes(Request $request){
$query = Frete::when($request->destino,function($q,$request) {
return $query->where('estado_destino_id', '=', $request->destino);
})->when($request->veiculo,function($q,$request) {
return $query->where('veiculo_id', '=', $request->veiculo);
})->get();
return response()->json($query);
}
Sometimes you may want clauses to apply to a query only when something
else is true. For instance you may only want to apply a where
statement if a given input value is present on the incoming request.
You may accomplish this using the when method.
I am having trouble creating a category tree structure in php and codeigniter ramework environments.
So now I want the structure of the data.
Data Example:
{
"category": [
{
"id" : "1",
"text" : "test1"
"children": false,
}, {
"id" : "2",
"text" : "test2",
"children": [
{
"children": false,
"id" : "3",
"text" : "test3"
}, {
"children": false,
"id" : "4",
"text" : "test4"
}, {
"children": false,
"id" : "5",
"text" : "test5"
}, {
"children": false,
"id" : "6",
"text" : "test7"
}
]
}
]
}
I'm having trouble creating an array for each json object's children
The query I am trying:
public function setCategoryTree($categoryUp = null)
{
$param = array();
$query = ' SELECT id, name, categoryUp
FROM categoryTable
WHERE categoryUp = ? ';
return $this->commerce_db->query($query)->result();
}
The controller I'm trying to:
public function getCategoryTree(){
$this->load->model('category_m');
$result = $this->category_m->setCategoryTree();
$resultData = array();
foreach($result as $value) {
$treeTmpData = array();
$treeTmpData['id'] = $value->id;
$treeTmpData['text'] = $value->text;
$treeTmpData['children'] = ????
$resultData[] = $treeTmpData;
}
echo json_encode($resultData, JSON_UNESCAPED_UNICODE);
}
Good luck to me
You can use this code for your purpose. I use recursion for getting childern.
Table structure is :
CREATE TABLE `categorytable` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) DEFAULT NULL,
`parent_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
);
Model methods are:
public function setCategoryTree() {
$categories = array();
$query = $this->db->query('SELECT id, name as text, parent_id as children FROM categoryTable WHERE parent_id IS NULL');
foreach ($query->result() as $row) {
$child = $this->getChilderen($row->id);
if (count($child) > 0) {
$row->children = $child;
} else {
$row->children = false;
}
$categories[] = $row;
}
return $categories;
}
private function getChilderen($parentId) {
$child = array();
$query = $this->db->query('SELECT id, name as text, parent_id as children FROM categoryTable WHERE parent_id = ' . $parentId);
if (count($query->result()) > 0) {
foreach ($query->result() as $i => $row) {
if ($row->children > 0) {
$row->children = $this->getChilderen($row->id);
}
$child[$i] = $row;
}
return $child;
} else {
return false;
}
}
Controller code:
public function getCategoryTree(){
$this->load->model('category_m');
$resultData = $this->category_m->setCategoryTree();
echo json_encode($resultData, JSON_UNESCAPED_UNICODE);
}
Hope, that will help you. Let me know if you stuck somewhere.
----------------------Code --------------------------
public function event_requests(){
$Uid = Input::get('Uid');
$token = Input::get('token_code');
$time = Input::get('time');
if(App_user::where('ID', '=', $Uid)->where('token_code', '=', $token)->count() > 0){
$result = DB::table('Ball_invites')
->join('Ball_users','Ball_users.ID', '=', 'Ball_invites.people')
->select('Ball_users.*', 'Ball_invites.Eid')
->Where('Ball_users.Pid', '=', $Uid)
->orWhere('Ball_users.ID', '=', $Uid)
->get();
foreach ($result as $val){
$eis[] = $val->Eid;
$eids = array_unique($eis);
}
$event = DB::table('Ball_event')->whereIn('ID', $eids)->get();
$resultdataa = array();
foreach($result as $new){
$resultdataa[$new->Eid] = $new;
}
$resultdata = json_decode(json_encode($resultdataa), true);
$data = array();
foreach($event as $key){
$data[$key->ID] = $key;
}
$dataa = json_decode(json_encode($data), true);
$final = array();
foreach($dataa as $key2=>$val2){
foreach($resultdata as $key1=>$val1){
if($key2 == $key1){
$arrs[] = $val2;
$arrss[] = $val1;
print_r($val1);
}
}
}
return Response::json(array('status'=>200,'result'=>$final));
} else {
return Response::json(array('status'=>'401','msg'=>'session expired'));
}
}
--------------------- Need Record like this ----------------------
Editor Note: the data structure below looks like it is desired to be JSON,
but I'm not sure what to make of the nested array in a bad location.
{
"status": 200,
"result": [
{
"ID": 63,
"Uid": 86,
"event_type": 1,
"event_title": "Testing",
"event_location": "Home",
[
{
"ID": 141,
"Pid": 139,
"fname": "Veronica",
"lname": "khiwani",
"nick_name": "Ronnie",
},
{
"ID": 141,
"Pid": 139,
"fname": "Veronica",
"lname": "khiwani",
"nick_name": "Ronnie",
}
]
},
{
"ID": 64,
"Uid": 139,
"event_type": 2,
"event_title": "cricket match",
"event_location": "london",
}
]
}