Joining multiple tables without any unique id for general search bar Laravel 7 giving sql error - laravel-7

I'm trying to make a general search bar which will fetch the related rows form 7 different tables but I am having problem in joining the 7 tables...
my code is
$query = $request->input('query');
$products = DB::table('manual_sellers')
->join('car_dealerships','manual_sellers.car_dealerships','=','')
->where('car_title' , 'like', "%$query%")
->orWhere('make', 'like', "%$query%")
->orWhere('make', 'like', "%$query%")
->orWhere('model', 'like', "%$query%")
->orWhere('manufact_year', 'like', "%$query%")
->orWhere('car_body', 'like', "%$query%")
->get();
when try to search then it throws error
how can I generally search a non unique value from 7 tables also appreciated if you have another good approach... because there will be tons of data to fetch in this query...
Thanks a lot

so i would like to post the answer to help others...
$query = $request->input('query');
$products1 = DB::table('car_dealerships')
->where('car_title' , 'like', "%$query%")
->orWhere('make', 'like', "%$query%")
->orWhere('model', 'like', "%$query%")
->orWhere('manufact_year', 'like', "%$query%")
->orWhere('car_body', 'like', "%$query%")
->get();
$products2 = DB::table('manual_sellers')
->where('car_title' , 'like', "%$query%")
->orWhere('make', 'like', "%$query%")
->orWhere('model', 'like', "%$query%")
->orWhere('manufact_year', 'like', "%$query%")
->orWhere('car_body', 'like', "%$query%")
->get();
after making two variables i simply merged the arrays like this
$data = $products1->merge($products2);
works for me that because the method i was trying before simply was collecting arrays of arrays in one array that needed two foreach loops to render values which was a pain....
but by merging like this it combined all arrays from their parent arrays in one parent array and there i got only one foreach loop which was needed...
thanks

Related

Suitescript N/Search Filter by custom sublist line field

I am trying to add a search filter for a custom line item field in a suitelet and it is returning no results.
function getExpenseSearch(soNum){
log.debug('getExpenseSearch entered')
log.debug('soNum: ' + soNum)
var billSearch = search.create({
type: 'transaction',
filters: [
[ 'type', search.Operator.ANYOF , ['VendBill']], 'and',
['mainline', search.Operator.IS,['F']], 'and',
['custcol_connected_so', search.Operator.ANYOF, [soNum]] ///<=== this is the problem why is it not registering?
],
columns: ['trandate',
'tranid',
'amount'
]
}).run().getRange({start: 0, end: 100})
log.debug('return billSearch[0].tranid: ' + billSearch[0].tranid) //<== always undefined
return billSearch
}
I have isolated the problem to the sublist field
custcol_connected_so is a List field (of sales orders)
soNum is the netsuite internal id of the record
I have already tried the following:
changed .IS to to .ANYOF
used TEXT value instead of recID
hardcoded the correct recID
used 'expense.custcol_connected_so (and other variations, shot in the dark)
input different syntax for create filter
In the records browser there is no join table for the vendorBill so I would think just the custcol_connected_so filter should work fine.
Taking another look there are a couple of issues.
Your syntax for getting the tranid is incorrect (or at least not supported) and you would not be able to get the mainline amount with a single query because you are only going to be able to return the line level amount. In the example below you could use ref.id to load the sales order or to do a lookup Fields call:
This works in my account:
require(['N/search'], search=>{
search.create({
type:'creditmemo',
filters:[
['mainline', 'is', 'F'], 'AND',
['custcol_linked_transaction', 'anyof', [2403605]]
],
columns:['tranid', 'custcol_linked_transaction']
}).run().each(ref=>{
console.log(ref.id, ref.getValue({name:'tranid'}), ref.getValue({name:'custcol_linked_transaction'}));
return false;
});
});
If soNum is the visible sales order number you'd need to get the SO's internal id in order to run that search. Consider:
function getExpenseSearch(soNum) {
log.debug('getExpenseSearch entered')
log.debug('soNum: ' + soNum)
var soInternalId = null;
search.create({
type: 'salesorder',
filters: ['tranid', 'is', soNum]
}).run().each(function(ref) {
soInternalId = ref.id;
return false;
});
var billSearch = search.create({
type: 'vendorbill',
filters: [
['mainline', 'is', 'F'], 'and',
['custcol_connected_so', 'is', soInternalId] ///<=== this is the problem why is it not registering?
],
columns: ['trandate',
'tranid',
'amount'
]
}).run().getRange({
start: 0,
end: 100
})
log.debug('return billSearch[0].tranid: ' + billSearch[0].tranid) //<== always undefined
return billSearch
}

How can we join 2 vertices in gremlin and get the desired output

I have vertex called "test" and "check"
test has fields like
g.V().hasLabel('test').valueMap(true).toList();
{ 'id': ['3130'], 'label': 'dev', 'mdate': ['2021-02-27T13:52:16.494Z'], 'mby': ['sync'],
'id': 'e8bbf1e1-7240-b5f2-cd55-b8558b02a93f', 'bName': ['STG '] }
check has fields like
g.V().hasLabel('check').valueMap(true).toList();
{ 'label': 'stag', 'mdate': ['2021-02-27T13:52:15.817Z'], 'mby': ['Test'], 'vname': ['STROE GMBH'], 'vnum': ['170010'],
'id': 'dcbbf1e1-70f9-aeff-828e-130be0186d81' }
how can we join both vertex and get the output data like below using gremlin query
{ 'id': '', 'label': '', 'mdate': '', 'mby': '', 'id':'', 'name':'', 'vname':'', 'vnum': '' }
You can do this by getting their elementMap and using a group step to merge the results. I included an example that uses the air routes data set so you can see the output format. I also added a version that should work with the data you provided.
gremlin> g.V(3,4).elementMap().unfold().group().by(keys).by(values)
==>[country:[US,US],code:[AUS,BNA],longest:[12250,11030],city:[Austin,Nashville],lon:[-97.6698989868164,-86.678199768
0664],type:[airport,airport],elev:[542,599],icao:[KAUS,KBNA],id:[3,4],label:[airport,airport],region:[US-TX,US-TN],ru
nways:[2,4],lat:[30.1944999694824,36.1245002746582],desc:[Austin Bergstrom International Airport,Nashville Internatio
nal Airport]]
Using your example you could do
g.V().hasLabel('test','check').
elementMap().
unfold().
group().
by(keys).
by(values)

Searching an array of items in NetSuite using SuiteScript 2

I am attempting to write a suitescript search that allows me to pass an array of identifiers to a particular field in Netsuite and return the results. I have tried 'ANYOF', 'ALLOF' and "WITHIN' but I keep getting errors
Here is my code so far:
if(params.type=='sku'){
var filter_name = 'itemid';
}else{
var filter_name = 'upccode';
}
var filters = [
search.createFilter({
name: filter_name,
operator: search.Operator.ANYOF,
values: ['HERHR5201','HERHR5202','HERHR5203']
}),
];
var s = search.create({
'type': record.Type.INVENTORY_ITEM,
'filters':filters,
}).run();
s = s.getRange(0,100);
return JSON.stringify(s);
Does anyone know the right sequence to create a multiple search of itemid's? Also, for a bonus, is there a way to have the resultset return the columns I need verses just the ideas? Do I need to createColumn?
You cannot use ANYOF, ALLOF, etc. when filtering a search on a text field. You'll need to create a filter expression with ORs to search on multiple values.
I would do this:
if(params.type=='sku'){
var filter_name = 'itemid';
}else{
var filter_name = 'upccode';
}
var filters = [
[filter_name, 'is', 'HERHR5201'], 'OR',
[filter_name, 'is', 'HERHR5202'], 'OR',
[filter_name, 'is', 'HERHR5203']
];
var s = search.create({
'type': record.Type.INVENTORY_ITEM,
'filters':filters
}).run();
As far as returning specific columns from your search, you'll need to use search.createColumn(), as you point out. So it'd be something like:
//Previous code...
var s = search.create({
'type': record.Type.INVENTORY_ITEM,
'filters':filters,
'columns': [search.createColumn({name: 'internalid'}),
search.createColumn({name: 'upccode'}),
search.createColumn({name: 'itemid'})
/*Other columns as needed*/]
}).run();
The provided answer is correct, however based on your example code provided I am assuming that the search needs to be created somewhat dynamically. Meaning the 'array of identifiers' you mention will not always be the same, nor will they always be the same length. In order to create a search that is completely dynamic based on incoming 'array of identifiers' you would need to get pretty creative. In the below solution I am assuming the function parameter 'params' is an object with a 'type' property, and an arrIn (array of strings) property. The search below uses the formula function 'DECODE', a description of which can be found here.
function execute(params) {
var filter_name;
var itemSearchObj;
var stringArr = '';
var arrIn = params.arrIn;
var i;
var count;
// create search filter type
filter_name = params.type === 'sku' ? 'itemid' : 'upccode';
// create stringArr using incoming arrIn
for (i = 0; arrIn && arrIn.length > i; i += 1) {
stringArr += i > 0 ? ", '" + arrIn[i] + "', 'true'" : "'" + arrIn[i] + "', 'true'";
}
if (arrIn.length > 0) {
itemSearchObj = nsSearch.create({
type: 'item',
filters: [
["formulatext: DECODE({" + filter_name + "}," + stringArr + ")", "is", 'true']
],
columns: [
'itemid', // dont need to get fancy here, just put the internal id of whichever fields you want in the columns
'description'
]
});
count = itemSearchObj.runPaged().count;
itemSearchObj.run().each(function (result) {
// Do things for each result
});
}
}
I found this quite a bit of a curveball as I was overthinking it. The search requires an array:
results = search.create({
type: search.Type.CUSTOMER,
filters: [],
columns: [ search.createColumn({ name: "internalid", sort: search.Sort.ASC }) ]
})
This filter array consists of a search term array and logical operators (AND, OR).
['fieldid', 'is', yourValue], // search term array
'AND' // logical operator
So you can create your own filter array, by pushing in the search terms and logical operators as required.
For example if you want to return the internal id for customer emails in an array:
let email = ['abc#test.com', 'def#test.com'];
let myFilter = createFilter(email);
function createFilter(email){
let filter = [];
email.forEach((result, index) => {
if(index > 0)
filter.push('OR'); // Logical Operator
filter.push(['email', 'is', result]);
});
return filter;
}
Variable myFilter will now equal:
[ ['email', 'is', 'abc#test.com'], 'OR', ['email', 'is', 'def#test.com'] ]
And can be directly referenced as the filter in the search.
let results = search.create({
type: search.Type.CUSTOMER,
filters: myFilter,
columns: [ search.createColumn({ name: "internalid", sort: search.Sort.ASC }) ]
})

Knex.js multiple orderBy() columns

Is it possible to do multiple orderBy() columns?
knex
.select()
.table('products')
.orderBy('id', 'asc')
The orderBy() chainable only takes a single column key and a sort value, but how can I order by multiple columns?
You can call .orderBy multiple times to order by multiple columns:
knex
.select()
.table('products')
.orderBy('name', 'desc')
.orderBy('id', 'asc')
The original answer is technically correct, and useful, but my intention was to find a way to programatically apply the orderBy() function multiple times, here is the actual solution I went with for reference:
var sortArray = [
{'field': 'title', 'direction': 'asc'},
{'field': 'id', 'direction': 'desc'}
];
knex
.select()
.table('products')
.modify(function(queryBuilder) {
_.each(sortArray, function(sort) {
queryBuilder.orderBy(sort.field, sort.direction);
});
})
Knex offers a modify function which allows the queryBuilder to be operated on directly. An array iterator then calls orderBy() multiple times.
The Knex orderBy function also receives an array:
knex('users').orderBy(['email', 'age', 'name'])
or
knex('users').orderBy(['email', { column: 'age', order: 'desc' }])
or
knex('users').orderBy([{ column: 'email' }, { column: 'age', order: 'desc' }])
You can use the following solution to solve your problem:
const builder = knex.table('products');
sortArray.forEach(
({ field, direction }) => builder.orderBy(field, direction)
);
orderBy accepts an array of type:
[
{column: 'id', order: 'asc'},
{column: 'name', order: 'desc'},
{column: 'created_at', order: 'desc'},
]
i have a function that takes a param from the request:
sort=id,name,-created_at
and builds an array that is passed to the queryBuilder
columns is an array with the accepted values of table columns
sort(model, sorts, columns) {
let confirmed = true;
sorts = sorts.split(',')
sorts.forEach((sort: string) => {
sort = sort.replace('-', '')
sort = sort.replace(' ', '')
confirmed = columns.includes(sort)
if (!confirmed) {
let index = sorts.indexOf(sort)
sorts.splice(index, 1)
}
})
let sortsArr = [];
sorts.forEach((sort) => {
if (sort.startsWith('-')) {
sort = sort.replace('-', '')
sortsArr.push({column: model.tableName + '.' + sort, order: 'desc'})
} else {
sortsArr.push({column: model.tableName + '.' + sort, order: 'asc'})
}
})
return sortsArr;
}
and then use it like this in the query
const sortsArr = sort(model, sorts, model.columns);
knex('users').orderBy(sortsArr)

Kohana Query Builder: and or where clause

->where('orders.date_paid', 'BETWEEN', array($from, $to))
->and_where('orders.status', '=', 'new')
->or_where('orders.status', '=', 'delivered')
I would like to show all rows where date_paid is between $from and $to, where status is either new or delivered.
When i add this or_where(), it ignores the BETWEEN $from and $to date_paid where clause.
How can i do this right?
You need to group your conditions.
->where('orders.date_paid', 'BETWEEN', array($from, $to))
->and_where_open()
->where('orders.status', '=', 'new')
->or_where('orders.status', '=', 'delivered')
->and_where_close();

Resources