Filtering a list in cakephp 3 - cakephp-3.0

I'd like to filter my items results in Cakephp 3, if the multiple rules are set.
For example before filtering result is all items list. If the category is set, the result is all items in that category. if the price is set all items in that category with that price
$item = $this->Items->find('all',['conditions' =>
IF ($category) RETURN Items.in.Category ELSE RETURN ALL,
IF ($price) RETURN Items.in.Price ELSE RETURN ALL,
]);
any idea?

You can do something like this,
$condition=[]; //Declaration of array for conditions
if(isset($category})
$condition[] = ['category ' => $category];
if($price)
$condition[] = ['price ' => $price];
And Now use this, in your find(condition)
$this->Items->find('all',['conditions' => ['AND'=>[$condition]]];
Note: - Use AND if both the variables are set, you want common results otherwise use OR instead of AND.
Hope This will help you.

Related

Add result of subquery to Eloquent query in Laravel 9

In Laravel 9 I am trying to add the result of a subquery to a query(for lack of better wording) and I am stuck. More concretely, I am trying to load all products and at the same time add information about whether the current user has bought that product.
Why do I want to do this?
I am currently loading all products, then loading all bought products, then comparing the 2 to determine if the user has bought a product, but that means extra queries which I would like to avoid. Pretend for the sake of this question that pagination doesn't exist(because when paginating the impact of those multiple queries is far diminished).
There is a many to many relationship between the 2 tables users and products, so these relationships are defined on the models:
public function products()
{
return $this->belongsToMany(Product::class);
}
and
public function users()
{
return $this->belongsToMany(User::class);
}
What I have tried so far:
I created a model for the join table and tried to use selectRaw to add the extra 'column' I want. This throws a SQL syntax error and I couldn't fix it.
$products = Product::query()
->select('id', 'name')
->selectRaw("ProductUser::where('user_id',$user->id)->where('product_id','products.id')->exists() as is_bought_by_auth_user")
->get();
I tried to use addSelect but that also didn't work.
$products = Product::query()
->select('id', 'name')
->addSelect(['is_bought_by_auth_user' => ProductUser::select('product_id')->where('user_id',$user?->id)->where('product_id','product.id')->first()])
->get();
I don't even need a select, I actually just need ProductUser::where('user_id',$user?->id)->where('product_id','product.id')->exists() but I don't know a method like addSelect for that.
The ProductUser table is defined fine btw, tried ProductUser::where('user_id',$user?->id)->where('product_id','product.id')->exists() with hardcoded product id and that worked as expected.
I tried to create a method on the product model hasBeenBoughtByAuthUser in which I wanted to check if Auth::user() bought the product but Auth wasn't recognized for some reason(and I thought it's not really nice to use Auth in the model anyway so didn't dig super deep with this approach).
$products = Product::query()
->select('id', 'name')
->addSelect(\DB::raw("(EXISTS (SELECT * FROM product_user WHERE product_users.product_id = product.id AND product_users.user_id = " . $user->id . ")) as is_bought_by_auth_user"))
->simplePaginate(40);
For all attempts $user=$request->user().
I don't know if I am missing something easy here but any hints in the right direction would be appreciated(would prefer not to use https://laravel.com/docs/9.x/eloquent-resources but if there is no other option I will try that as well).
Thanks for reading!
This should do,
$id = auth()->user()->id;
$products = Product::select(
'id',
'name',
DB::raw(
'(CASE WHEN EXISTS (
SELECT 1
FROM product_users
WHERE product_users.product_id = products.id
AND product_users.user_id = '.$id.'
) THEN "yes" ELSE "no" END) AS purchased'
)
);
return $products->paginate(10);
the collection will have purchased data which either have yes or no value
EDIT
If you want eloquent way you can try using withExists or withCount
i.e.
withExists the purchased field will have boolean value
$products = Product::select('id', 'name')->withExists(['users as purchased' => function($query) {
$query->where('user_id', auth()->user()->id);
}]);
withCount the purchased field will have count of found relationship rows
$products = Product::select('id', 'name')->withCount(['users as purchased' => function($query) {
$query->where('user_id', auth()->user()->id);
}]);

Why 'where' return all data in laravel

I am applying search filter in my project so first of all I get data from multiple tables and store in two different variables and then merge these two variable into one so I can filter data from that merged variable. So my code is like that
$data1=Model::query()
->Join('...')
->leftJoin('...')
->where('id',login_user)
->select(...)
->whereRaw('id IN (select MAX(id) FROM table GROUP BY name)')
->groupBy('name')
->get();
$data2=Model2::query()
->leftJoin(...)
->select(...)
->where('id',login_user)
->whereNotIn(..)
->get();
both data1 and data2 return same column with different values so I merge both variable like that
$results = $data1->concat($data2);
No when I already get data so now I need to add filter data from $results so i make post method for that .
so When user request to filter data with name I write query like that
if ($request->name!="") {
$results->when(request('name'), function($q){
$q->Where('name', request('name'));
});
}
$records = $results;
return response()->json(['success'=>true,'message'=>'success', 'data' => $records]);
But that query is not filtering the data and return me all data.I am new in laravel so I don't know what I have done wrong in that any favour will be helpful for me ,thanks.
if (request()->has('name')) {
$results->when(request()->get('name'), function($q){
return $q->where('name', request()->get('name'));
});
}
$records = $results;
return response()->json(['success'=>true,'message'=>'success', 'data' => $records]);
As you use 'when()', you can drop the if expression all together:
$results->when(request()->has('name'), function($q){
return $q->where('name', request()->get('name'));
});
$records = $results;
return response()->json(['success'=>true,'message'=>'success', 'data' => $records]);
request() is a Laravel helper for Request $request
Edit: the where() clause in the ORM is with a small 'w', not 'W' as in orWhere

Multiple Fields with a GroupBy Statement in Laravel

Already received a great answer at this post
Laravel Query using GroupBy with distinct traits
But how can I modify it to include more than just one field. The example uses pluck which can only grab one field.
I have tried to do something like this to add multiple fields to the view as such...
$hats = $hatData->groupBy('style')
->map(function ($item){
return ['colors' => $item->color, 'price' => $item->price,'itemNumber'=>$item->itemNumber];
});
In my initial query for "hatData" I can see the fields are all there but yet I get an error saying that 'colors', (etc.) is not available on this collection instance. I can see the collection looks different than what is obtained from pluck, so it looks like when I need more fields and cant use pluck I have to format the map differently but cant see how. Can anyone explain how I can request multiple fields as well as output them on the view rather than just one field as in the original question? Thanks!
When you use groupBy() of Laravel Illuminate\Support\Collection it gives you a deeper nested arrays/objects, so that you need to do more than one map on the result in order to unveil the real models (or arrays).
I will demo this with an example of a nested collection:
$collect = collect([
collect([
'name' => 'abc',
'age' => 1
]),collect([
'name' => 'cde',
'age' => 5
]),collect([
'name' => 'abcde',
'age' => 2
]),collect([
'name' => 'cde',
'age' => 7
]),
]);
$group = $collect->groupBy('name')->values();
$result = $group->map(function($items, $key){
// here we have uncovered the first level of the group
// $key is the group names which is the key to each group
return $items->map(function ($item){
//This second level opens EACH group (or array) in my case:
return $item['age'];
});
});
The summary is that, you need another loop map(), each() over the main grouped collection.

one to many query with where Has returns unwanted results

I have a query and don't find the correct solution for this:
$orders = Shipping::with('orderitems')
->whereHas('orderitems', function($query) {
$query->where('status','=',NULL);
})
->paginate(10);
I'm querying a one to many relationship
public function orderitems() {
return $this->hasMany('OrderItems');
}
Above query returns the correct resultset when all entries within 'orderItems' fit the condition, having status 'NULL'. The problem is, when I have an order with 2 items and one of the two items doesn't have status 'NULL', both items are returned though I only want the item which actually has status 'NULL' being returned.
I've tried it with a whereNested query and a query scope, but I think this is not the solution to the problem. Can someone assist?
whereHas will actually filter Shipping based on if they have at least one orderitem that matches the condition. I'm pretty sure what you want is use with with a condition:
$orders = Shipping::with(['orderitems' => function($query){
$query->where('status','=',NULL);
}])->paginate(10);
Edit
Add a whereHas if you also want only order with at least one item with status NULL:
$orders = Shipping::with(['orderitems' => function($query){
$query->where('status','=',NULL);
}])->whereHas('orderitems', function($query){
$query->where('status','=',NULL);
})->paginate(10);

Codeigniter mysql where not equal to query

Mysql codeigniter query is not working properly.
Suppose if mysql table looks like this:
user_id|user_name
1|john
2|alex
3|sam
Here user_name is unique
The following query should return false if user_name=john and user_id=1 and true if say user_name=john and user_id=2.
$this->db->get_where('user', array('user_name' => $name,'user_id !=' => $userid));
But it returns true in the case user_name=john and user_id=1.
Can anyone suggest me an alternative way of querying not equal to.
print($this->db->last_query()) gives:
SELECT * FROM (user) WHERE user_name = 'john' AND user_id != '1'
Why dont you use simple $this->db->query('your query');
Simply try this, Add the desired condition in the where function.
$this -> db -> where('invitee_phone !=', $user_phone);
You can go follwoing way too. It work for me
$total = 5;
$CI = get_instance();
$CI->load->database();
$CI->db->order_by('id','asc');
$topusers = $CI->db->get_where('users',array('user_type != 1 && `status` =' => 1),$total,0);
echo $CI ->db ->last_query();
die;
and if still not work for you can go with #rohit suggest: $this->db->query('your query');
Type 1:
Using ->where("column_name !=",$columnname) is fine for one column.
But if you want to check multi columns, you have to form an array inside where clause.
Like this
$whereArray = array(
"employee_name" => $name,
"employee_id !=" => $id,
);
$this->db->select('*')->from('employee')->where($whereArray);
Type 2:
We can just write exactly what we want inside where.
Like
$thi->db->where(("employee_id =1 AND employee name != 'Gopi') OR designation_name='leader#gopis clan'");
Type 2 is good for working with combining queries, i mean paranthesis "()"
you can follow this code:
$query = $this->db->select('*')->from('employee')->where('user_name', $name)->where('user_id !=', $userid)->get();
$last_query = $this->db->last_query();
$result = $query->result_array();
if you pass $name = 'john' and $userid = '1' then it return empty array.
The problem with using $this->db->query('your query'); is that it is not portable. One of the most important reasons to embrace the query builder methods is so that no matter what database driver you use, CodeIgniter ensures that the syntax is appropriate.
If a bit of discussion was possible, I'd probably like to hear why you need composite primary identifiers in your table and I'd like to see what your table schema looks like. However, I think the time for discussion has long passed.
Effectively, you want to return a boolean result stating the availability of the combination of the username AND the id -- if one is matched, but not both, then true (available).
To achieve this, you will want to search the table for an exact matching row with both qualifying conditions, count the rows, convert that integer to a boolean, then return the opposite value (the syntax is simpler than the explanation).
Consider this clean, direct, and portable one-liner.
return !$this->db->where(['user_name' => $name,'user_id' => $userid])->count_all_results('user');
this will return false if the count is > 0 and true if the count is 0.