laravel query builder to add and or condition - mysql

Receiving the request in array format
[
[
[
'condition1',
'value1',
],
[
'condition2',
'value2',
],
],
[
'condition3',
'value4',
]
]
Im trying to build query builder with values1 and values 2 in 'or' condition and value3 in 'and' condition
$result = DB::table('table ')
foreach($values as $value){ //
$result->where(function ($qry) use ($value) { // array 0,1 with and condition
foreach($value as $val){ // values1 , values2
$qry->where();
}
});
}
How to add 'or' condition between the values1 and values2 and then 'and' condition with value3.

Don't need any loop, you need sub query, like this :
$result = DB::table('table')
->where(function($query) use($value1) {
$query->where('condition1', $value1)
->orWhere('condition2', $value1);
})
->where('condition3', $value2)
->get();

Related

Can't Insert an array in table column, Laravel

I need to insert an array in a table column with other non array inputs, But each time it's inserting a string "Array" ,
My codes are :
$post_data['product_category'] = "Goods";
$post_data['product_profile'] = "physical-goods";
for ($i = 1; $i < count($request->package_type_id); $i++) {
$answers[] = [
$post_data['package_type_id'] =$request->package_type_id,
];
}
$update_product = DB::table('orders')
->where('transaction_id', $post_data['tran_id'])
->updateOrInsert([
'name' => $post_data['cus_name'],
'email' => $post_data['cus_email'],
'phone' => $post_data['cus_phone'],
'amount' => $post_data['total_amount'],
'status' => 'Pending',
'address' => $post_data['cus_add1'],
'transaction_id' => $post_data['tran_id'],
'currency' => $post_data['currency'],
'package_type_id' => implode($answers,',')
]);
You have gone a long way, I think you just want to make a string from the $request->package_type_id which I assume is an array.
$post_data['product_category'] = "Goods";
$post_data['product_profile'] = "physical-goods";
$post_data['package_type_id'] = implode(',', $request->package_type_id);
$update_product = DB::table('orders')
->where('transaction_id', $post_data['tran_id'])
->updateOrInsert([
// ...
'package_type_id' => $post_data['package_type_id']
]);
Also note that the syntax for implode is implode(glue, array) not the other way around.

Looping Array of Json to Database Laravel?

I have Json Data like this :
$data = '[
{
"OrderId": "1038806370",
"qtty": "1",
"Item": "Strawberry 250 gr",
"SKU": "20091"
},
{
"OrderId": "1038806370",
"qtty": "2",
"Item": "Strawberry 130 gr",
"SKU": "20092"
},
{
"OrderId": "1038806370",
"qtty": "1",
"Item": "Strawberry 130 gr",
"SKU": "20092"
}
]';
and I want to Save in my database MySql using PHP Laravel,...
I Want To save data from json to my table, there are table Order values [orderID,...] and OrderDetail values [orderID, SKU, Qty]
This is my code in controller
$order = json_decode($data, true);
foreach ($order as $ord) {
$check = Order::where('orderid', $ord['OrderId'])->get();
if (count($data) > 0) {
OrderDetail::firstOrCreate([
'order_id' => $ord['OrderId'],
'sku_id' => $ord['SKU'],
'qty' => $ord['qtty']
]);
} else {
Order::create([
'orderid'=> $ord['OrderId'],
]);
OrderDetail::firstOrCreate([
'order_id' => $ord['OrderId'],
'sku_id' => $ord['SKU'],
'qty' => $ord['qtty']
]);
}
}
but i dont get what i want, I get QTY of SKU 20091 is 2 but actual json data is 3
I'm not sure why you're counting the $data instead of $check variable. You don't really need the $check variable either though. I'll rewrite your code below.
$order = json_decode($data, true);
foreach ($order as $ord) {
// use EXIST query to check if Order exists or not.
if (Order::where('orderid', $ord['OrderId'])->exists())
OrderDetail::firstOrCreate([
'order_id' => $ord['OrderId'],
'sku_id' => $ord['SKU'],
'qty' => $ord['qtty']
]);
} else {
Order::create([
'orderid'=> $ord['OrderId'],
]);
OrderDetail::firstOrCreate([
'order_id' => $ord['OrderId'],
'sku_id' => $ord['SKU'],
'qty' => $ord['qtty']
]);
}
}
But your if/else could also be removed by using the firstOrCreate() method.
$orders = json_decode($data, true);
foreach ($orders as $order) {
// Get Order Model with orderid = $order['OrderId'] or create it if it doesn't exist
$model = Order::firstOrCreate([
'orderid'=> $order['OrderId']
]);
// Get OrderDetail with provided SKU, qtty and orderid or create it if it doesn't exist.
OrderDetail::firstOrCreate([
'order_id' => $model->orderid
'sku_id' => $order['SKU'],
'qty' => $order['qtty']
]);
}
You could also do it inline.
$orders = json_decode($data, true);
foreach ($orders as $order) {
OrderDetail::firstOrCreate([
'order_id' => Order::firstOrCreate(['orderid'=> $order['OrderId']])->orderid,
'sku_id' => $order['SKU'],
'qty' => $order['qtty'],
]);
}

how to id as key in mysql select return

I need return of my mysql query
from
SELECT name as id FROM table
but I need return like this in mysql (I wrote it in an array because it's easy to write)
[
20: 'Jack',//20 is id from table and Jack is name from table
40: 'Nano',
49: 'Hakase'
]
Use WHERE condition
SELECT * FROM table WHERE ID = yourId
just replace yourId for the ID number you want.
First, select all id and name using
SELECT id, name FROM table SOME CONDITIONS
this query would return a result like
$result = [
[ id => 1, name => 'name' ],
[ id => 1, name => 'name' ],
[ id => 1, name => 'name' ],
[ id => 1, name => 'name' ],
]
then arrange array
$accepted_output = array_column($result, 'id', 'name')
$accepted_output = [
[ 1 => 'name' ],
[ 1 => 'name' ],
[ 1 => 'name' ],
[ 1 => 'name' ],
]
array_column docs - https://www.php.net/manual/en/function.array-column.php
You want to return the ID and the name so you should rewrite your query to:
SELECT id,name FROM table
You should use commas to seperate field names.
For more information you can do some reading here.

Yii2. How to build subexpression

How can i build query with subexpression, without using yii\db\Expression and raw sql. For example this:
SELECT * FROM user WHERE archived = 3 AND ((group = 2 AND status = 3) OR (group = 3 AND status = 2));
You can build such condition using array expressions:
$users = (new Query())
->from('user')
->where(['archived' => 3])
->andWhere([
'or',
[
'group' => 2,
'status' => 3,
],
[
'group' => 3,
'status' => 2,
],
])
->all();

cakephp query find_in_set on single column with multiple searched keywords not working

I want to find all the records from column who have any keyword match with column data:
It works fine if searching single search keyword in column having comma separated values like below code: Cakephp 3.4 version
$posts = TableRegistry::get('Posts');
$search_keywords = array_filter(explode(' ', $search_string));
$option = [
'contain' => false,
'conditions' => [
"find_in_set('New', Posts.title)",
],
'order' => ['Posts.created DESC']
];
$allpost = $posts->find('all',$option)->toArray();
Note: i want all the words from string should be search with column title, its not mandatory to have comma separated records:
$search_keyword = "New car in new delhi";
so i want code to be like below :
$search_keyword = "New car in new delhi";
$search_keywords = array_filter(explode(' ', $search_string));
$option = [
'contain' => false,
'conditions' => [
"find_in_set({$search_keywords}, `Posts`.title)",
],
'order' => ['Posts.created DESC']
];
$allpost = $posts->find('all',$option)->toArray();
Great Thanks in advance!!!
I found the solution:
First make column fulltext index then add below code:
$search_string = "New car in new delhi";
$option = [
'contain' => false,
'conditions' => [
"MATCH (title) AGAINST ('$search_string')"
],
'order' => ['Posts.created DESC']
];
$allpost = $posts->find('all',$option)->toArray();