How to create query condition where comparing field is equal to a dynamic value in Cakephp 3 - cakephp-3.0

I'm trying to create a query like this:
$spreadsheet = $this->Spreadsheets->get($id, [
'contain' => [
'SpreadsheetTypes.CentersTypes' => function ($q) {
return $q->matching('Centers', function ($q) {
return $q->where(['Centers.id' => 5]);
})->contain(['Items']);
}
]
]);
$id value is passed by parameter. But I need to change
return $q->where(['Centers.id' => 5])
because I need to compare 'Centers.id' with center_id value that I will get on this query. I mean, Spreadsheets has a center_id field, so, I need to compare with it.
Any idea?

add "use" after function ($q)
exemple
return $q->matching('Centers', function ($q) use($foo) {
return $q->where(['Centers.id' => $foo]);
})->co

Related

Yii2: Filter query by pivot table when using `joinWith()`

Take the following sample Cart model. It has a CartItem "pivot record/table" which links it to Item.
class Cart extends ActiveRecord {
public function getCartItems() {
return $this
->hasMany(CartItem::class, ['cart_id' => 'id'])
->inverseOf('cart');
}
public function getItems($callback = null) {
return $this
->hasMany(Item::class, ['item_id' => 'id'])
->via('cartItems', $callback);
}
}
(Example #1) At this point I would be able to filter either by Item's activequery or CartItem's query like so:
$booksAddedToCartSinceYesterday = $cart
->getItems(function($cartItemQuery) {
$cartItemQuery->andWhere('cartItem.created_at > NOW()');
})
->andWhere(['item.category' => 'books']);
(Example #2) But how do I accomplish the same when I use the static find() method in combination with joinWith()? In the following example I am only able to filet by Item's ActiveQuery, but I no longer have any reference to the CartItem's ActiveQuery object:
$booksAddedToCartSinceYesterday = Cart::find()
->andWhere(['cart.user_id' => $some_user_id])
->joinWith([
'items' => function($itemQuery) {
$itemQuery->andWhere(['item.category' => 'books']);
},
]);
How do I modify the code above so that I am able to filter CartItem junction table records like I did in my example #1? How do I access the junction ActiveQuery object so that I can call $cartItemQuery->andWhere('cartItem.created_at > NOW()');?
you can pass any variable value in anonymous function with use keyword link below
make your magic code here for filter or any
->joinWith([
'items' => function($itemQuery) use ($var1,$var2){
$itemQuery->andWhere(['item.category' => 'books']);
$itemQuery->andWhere(['some_condition' => $var1]); <<<---------
},
]);

Yii2 SearchModel query - map integer values to strings

What I am trying to achieve:
I have a table with a type field which holds integer values. These integer values represent different strings.
I want to be able to search the table using the string values that the integers represent.
E.g type = abc rather than type = 0.
What have I tried:
I have created a query class for the model and tried to make use of the $boolean_map property:
class ReportQuery extends FilterableQuery
{
protected $filterable = [
'type' => 'LIKE',
'removed_the_rest'
];
protected $boolean_map = ["type" => [ 'addacs' => 0, "arudd" => 1,]];
}
Then I have overridden the find method of the model to use the query class:
public static function find()
{
$query = new ReportQuery(get_called_class());
return $query;
}
And in the search model I have:
public function search($params)
{
$query = Report::find();
$dataProvider = new ActiveDataProvider([
'query' => $query
]);
$this->load($params, '');
if (!$this->validate()) {
return $dataProvider;
}
// grid filtering conditions
$query->andFilterWhere([
'type' => $this->type,
]);
$query->andFilterWhere(['like', 'type', $this->type]);
return $dataProvider;
}
When searching by the string values I get an empty result. Searching by the integer values produces the data.
Any help is appreciated. Thanks.
Maybe it's better for you to make filter on that column instead of searching by string. You can do it for string as follows.
$filter = [
'example1' => 1,
'example2' => 2,
'example3' => 3,
];
$query->andFilterWhere(['like', 'type', $this->filter[$this->type]);
or in this place
// grid filtering conditions
$query->andFilterWhere([
'type' => $this->filter[$this->type],
])
also you can make filter dropdown on column, and for dropdown of that filter you can pass this array and just do
$query->andFilterWhere([
'type' => $this->type,
])
Why do you create mapping mechanism in query object? Okay, you show integer type as a string in frontend of your application, but the query shouldn't have details of representation. You should map string type to integer type in your search model. For example:
class ReportSearchModel extends ReportModel
{
public function mapType($value)
{
$items = [
'addacs' => 0,
'arudd' => 1
];
return array_key_exists($value, $items) ? $items[$value] : null;
}
public function search($params)
{
//another code
$query->andFilterWhere([
'type' => $this->mapType($this->type),
])
//another code
}
}
The alternative way is using an enum instead of mapping.

Returning multiple JSON from controller in Laravel

I have something like this in the route:
Route::post('/iteminfo/{item_id}','itemcontroller#get_item_info');
And something like this in the controller
public function get_item_info($request)
{
$item_image = Item_Image->where("item_id",$request)->first();
$item_something = Item_Something->where("item_id",$request)->first();
$item_more = Item_More->where("item_id",$request)->first();
return Response::json($item_image);
}
I want to return the 3 things but with return Response::json() I can only return 1 statement (as far as I know). Is there any way to return all of them?
You can pass an array as the json response. So craft an array based on your data and use it.
return Response::json(array(
'item_image' => $item_image,
'item_something' => $item_something,
'item_more' => $item_more,
));
Since it requires an Array parameter so you can construct an array from the variables
return response()->json(['item_image ' => $item_image, 'item_something' => $item_something, 'item_more' => $item_more ]);
Or
return Response::json(['item_image ' => $item_image, 'item_something' => $item_something, 'item_more' => $item_more ]);

Laravel: How can I keep the orderBy when I convert to json?

I am generating a query that returns results from a camp. I am sending it to another platform that digests this data as an array.
I am trying to return my kickoffs in order by score (highest to lowest).
Here is what the query looks like:
$camp = Camp::where('id', $camp_id)
->where('approved', 1)
->with(['athletes' => function ($q) use ($camp_id) {
$q->with(['kickoffs' => function ($q) use ($camp_id) {
$q->where('camp_id', $camp_id);
}]);
$q->with(['kickoff_results' => function ($q) use ($camp_id) {
$q->where('camp_id', $camp_id);
$q->orderBy('score', 'desc');
}]);
...
})->first();
...
if ($camp) {
return response()->json([
'data' => $camp,
...
], 200);
}
In my other system this is how I am outputting it:
foreach ($context['camp']['data']['athletes'] as $athlete) {
...
if (!empty($athlete['kickoff_results'])) {
...
}
}
When the result is finally rendered, it seems there is no order whatsoever.
Thank you for any suggestions!

multiple where condition in yii2

Hi, my problem is simple i want to add multiple where condition on yii2 Query bulder, but i don't know what doing.
my code like that
public function searchForTrip($params, $extraParams, $filter) {
$query = Boatinformation::find()
->where(['what_island' => $params['BoatinformationSearch']['what_island']])
->all();
if(isset($filter)) {
foreach ($filter as $key => $value) {
->andFilterWhere([$value => 1])
}
}
return $query;
}
this is not working
please someone help me
You can do in several way and you can found an useful guide in this doc http://www.yiiframework.com/doc-2.0/guide-db-query-builder.html
you can use string format specifying the condition as a string :
$query->where('your_field1 =1 and your_field2 = 2');
You can use hash format and
$query->where([
'your_field1' => 10,
'your_field2' => null,
'your_field3' => [4, 8, 15],
]);
You can use operator format
$query->where(['and' , 'your_field1', 10, ]);
and you can also use
andWhere('your_field'=> $your_value ),
You should write something like
public function searchForTrip($params, $extraParams, $filter) {
$query = Boatinformation::find()
->where(['what_island' => $params['BoatinformationSearch']['what_island']])
if(isset($filter)) {
foreach ($filter as $key => $value) {
$query->andFilterWhere([$value => 1])
}
}
return $query;
}
$query->andFilterWhere() add where condition if $value exist,
$query->andWhere() add where condition always
and if you want to return objects instead of query you should return $query->all();