PHP Laravel - how to select mysql table names by name template - php

$nameTemplate=“prefix_“;
$tables = DB::select(“SHOW TABLES LIKE ‘$nameTemplate%’“);
this returns as prefix_somename, so prefixanothername too. How to do to only first result returns?
$nameTemplate = ‘prefix_‘;
$tables = DB::connection()->getDoctrineSchemaManager()->listTableNames();
$tables = collect($tables);
$tables->contains(function ($item) use ($nameTemplate) {
return (strpos($item, $nameTemplate) !== false);
});
this returns all tables. Where is an error?

You can try to filter the results, like this:
$tables = collect($tables)->filter(function($item) use ($nameTemplate) {
return strpos($item, $nameTemplate) !== false;
});
$tables here should contain only the tables based on your filter.

I found that first part of question expression works if to use backslash before "_"
$nameTemplate=“prefix\_“;

try this
$nameTemplate="prefix_";
$tableNames = \Schema::getConnection()->getDoctrineSchemaManager()->listTableNames();
foreach ($tableNames as $tableNameValue)
{
if (strpos($tableNameValue, $nameTemplate) !== false)
{
dd('table found in serach criteria ');
}
else
{
dd('table not found in serach criteria ');
}
}

Related

How can i make associations in Shopware 6?

Basically I want the same result that this SQL would return:
SELECT id FROM property_group_option opt
LEFT JOIN property_group_option_translation tra
ON opt.id = tra.property_group_option_id
WHERE opt.property_group_id = <id> AND tra.name = "<name>"
The way to go described in the Shopware documentation does not seem to get the right result. I have tried the following:
$criteria = (new Criteria())
->addFilter(new EqualsFilter('property_group_id', $propertyGroupId))
->getAssociation('property_group_option_translation')
->addFilter(new EqualsFilter('name', $value));
$result = $this->propertyGroupOptionRepository->search($criteria, Context::createDefaultContext())->first()->getId();
I did find a workaround which does not seem to be the way to go (and is also not the best performing), but it did return the right result.
$criteria = (new Criteria());
$criteria->addFilter(new EqualsFilter('name', $value));
$criteria->getAssociation('property_group_option')
->addFilter(new EqualsFilter('groupId', $propertyGroupId));
$translation = $this->propertyGroupOptionTranslationRepository->search($criteria, Context::createDefaultContext())->first()
if($translation !== null) {
$criteria = (new Criteria([$translation->get('propertyGroupOptionId')]));
$result = $this->propertyGroupOptionRepository->search($criteria, Context::createDefaultContext())->first()->getId();
}
is there a proper solution for that?
You are using the table name. Try to use the model name instead.
You have to use addAssociation() first - getAssociation() seems to return a new Criteria instance which is later not used in the actual query, if the association did not exist before:
See in the code.
public function getAssociation(string $path): Criteria
{
$parts = explode('.', $path);
$criteria = $this;
foreach ($parts as $part) {
if ($part === 'extensions') {
continue;
}
if (!$criteria->hasAssociation($part)) {
$criteria->associations[$part] = new Criteria(); // this is returned, but not stored
}
$criteria = $criteria->associations[$part];
}
return $criteria;
}

Filtering search engine data

I have a problem with filtering information using a form,
Here is my code
$cooperation = Cooperation::with('user')->get();
$search_results = [];
$search = Input::get('q');
$category = Input::get('c');
$land = Input::get('l');
if(!empty($search || $category || $land)){
$search_results = $cooperation;
if (!empty($search)){
$search_results = $search_results->where('title', 'like', '%'. $search .'%');
}
if (!empty($category)){
$search_results = $search_results->where('category', $category);
}
if (!empty($land)){
$search_results = $search_results->where('land', $land);
}
$exist_s = true;
$not_s = false;
return view('cooperation.index', compact('cooperation', 'search_results', 'exist_s', 'not_s'));
}
else{
$not_s = true;
$exist_s = false;
return view('cooperation.index', compact('cooperation', 'search_results', 'exist_s', 'not_s'));
}
After retrieving data from the form I am trying to filter through the array in sequence by each variable but nothing happens, the only thing that works is filtering in $ category but I do not know why the rest does not work.
I'm looking for a solution as to how to filter data efficiently, I could do it if () after if () but with more variables it would be a very inefficient solution.
If anyone has any idea in advance thank you.
If you want to have an efficient search according to your requirements you can have following input variables:
$columns, $searchColumns, $search_operator, $search_input
$columns can be the columns through which you can order, searchColumns can be the columns through which you want to have search and search_operator as in like, <, <=, in, >, >= etc, you can even improvise with the direction as asc or dsc in values, so you can have something like this:
return $query
->orderBy($request->column, $request->direction)
->where(function($query) use ($request, $searchColumns) {
if($request->has('search_input')) {
for($x = 0, $l = count($searchColumns); $x < $l; $x++) {
if($request->search_operator == 'in') {
$query->whereIn($searchColumns[$x], explode(',', $request->search_input));
} else if($request->search_operator == 'like') {
$query->orWhere($searchColumns[$x], 'LIKE', '%'.$request->search_input.'%');
}
else {
$query->orWhere($searchColumns[$x], $this->operators[$request->search_operator], $request->search_input);
}
}
}
})
->paginate(100);
I don't know why your request is not working. However, if you are looking for a generic way of filtering your results I believe a simple foreach loop with an array of your filters variables would do the trick :
$filters = []; //your variables such as category and land go in there
foreach ($filters as $column => $value){
$search_results = $search_results->where($column, $value);
}

Check whether the given two words are existing in a PHP string

I want to check if a string contains two specific words.
For example:
I need to check if the string contains "MAN" & "WAN" in a sentence like "MAN live in WAN" and returns true else false.
What I've tried is looping string function in a conditional way:-
<?php
$data = array("MAN","WAN");
$checkExists = $this->checkInSentence($data);
function checkInSentence( $data ){
$response = TRUE;
foreach ($data as $value) {
if (strpos($string, $word) === FALSE) {
return FALSE;
}
}
return $response;
}
?>
Is it the right method or do I've to change it? How to implement this any suggestions or idea will be highly appreciated.
Note: data array may contain more than two words may be. I just need check whether a set of words are exists in a paragraph or sentence.
Thanks in advance !
It's alsmost good. You need to make it set the response to false if a word is not included. Right now it'll always give true.
if (strpos($string, $word) === FALSE) {
$response = FALSE;
}
Try this:
preg_match_all("(".preg_quote($string1).".*?".preg_quote($string2).")s",$data,$matches);
This also should work!
$count = count($data);
$i = 0;
foreach ($data as $value) {
if (strpos($string, $value) === FALSE) {
#$response = TRUE; // This is subject to change so not reliable
$i++;
}
}
if($i<$data)
response = FALSE;

Multi-dimensional array search to preserve parent

TL;DR
I have this data: var_export and print_r.
And I need to narrow it down to: http://pastebin.com/EqwgpgAP ($data['Stock Information:'][0][0]);
How would one achieve it? (dynamically)
I'm working with vTiger 5.4.0 CRM and am looking to implement a function that would return a particular field information based on search criteria.
Well, vTiger is pretty weakly written system, looks and feels old, everything comes out from hundreds of tables with multiple joins (that's actually not that bad) etc., but job is job.
The need arose from getting usageunit picklist from Products module, Stock Information block.
Since there is no such function as getField();, I am looking forward to filter it out from Blocks, that is actually gathering the information about fields also.
getBlocks(); then calls something close to getFields();, that again something close to getValues(); and so on.
So...
$focus = new $currentModule(); // Products
$displayView = getView($focus->mode);
$productsBlocks = getBlocks($currentModule, $displayView, $focus->mode, $focus->column_fields); // in theory, $focus->column_fields should/could be narrowed down to my specific field, but vTiger doesn't work that way
echo "<pre>"; print_r($productsBlocks); echo "</pre>"; // = http://pastebin.com/3iTDUUgw (huge dump)
As you can see, the array under the key [Stock Information:], that actually comes out from translations (yada, yada...), under [0][0] contains information for usageunit.
Now, I was trying to array_filter(); the data out from there, but only thing I've managed to get is $productsBlocks stripped down to only contain [Stock Information:] with all the data:
$getUsageUnit = function($value) use (&$getUsageUnit) {
if(is_array($value)) return array_filter($value, $getUsageUnit);
if($value == 'usageunit') return true;
};
$productsUsageUnit = array_filter($productsBlocks, $getUsageUnit);
echo "<pre>"; print_r($productsUsageUnit); echo "</pre>"; // = http://pastebin.com/LU6VRC4h (not that huge of a dump)
And, the result I'm looking forward to is http://pastebin.com/EqwgpgAP, that I've manually got by print_r($productsUsageUnit['Stock Information:'][0][0]);.
How do I achieve this? (dynamically...)
function helper($data, $query) {
$result = array();
$search = function ($data, &$stack) use(&$search, $query) {
foreach ($data as $entry) {
if (is_array($entry) && $search($entry, $stack) || $entry === $query) {
$stack[] = $entry;
return true;
}
}
return false;
};
foreach ($data as $sub) {
$parentStack = array();
if ($search($sub, $parentStack)) {
$result[] = $parentStack[sizeof($parentStack) - 2];
}
}
return $result;
}
$node = helper($data, 'usageunit');
print_r($node);

Filter a set of bad words out of a PHP array

I have a PHP array of about 20,000 names, I need to filter through it and remove any name that has the word job, freelance, or project in the name.
Below is what I have started so far, it will cycle through the array and add the cleaned item to build a new clean array. I need help matching the "bad" words though. Please help if you can
$data1 = array('Phillyfreelance' , 'PhillyWebJobs', 'web2project', 'cleanname');
// freelance
// job
// project
$cleanArray = array();
foreach ($data1 as $name) {
# if a term is matched, we remove it from our array
if(preg_match('~\b(freelance|job|project)\b~i',$name)){
echo 'word removed';
}else{
$cleanArray[] = $name;
}
}
Right now it matches a word so if "freelance" is a name in the array it removes that item but if it is something like ImaFreelaner then it does not, I need to remove anything that has the matching words in it at all
A regular expression is not really necessary here — it'd likely be faster to use a few stripos calls. (Performance matters on this level because the search occurs for each of the 20,000 names.)
With array_filter, which only keeps elements in the array for which the callback returns true:
$data1 = array_filter($data1, function($el) {
return stripos($el, 'job') === FALSE
&& stripos($el, 'freelance') === FALSE
&& stripos($el, 'project') === FALSE;
});
Here's a more extensible / maintainable version, where the list of bad words can be loaded from an array rather than having to be explicitly denoted in the code:
$data1 = array_filter($data1, function($el) {
$bad_words = array('job', 'freelance', 'project');
$word_okay = true;
foreach ( $bad_words as $bad_word ) {
if ( stripos($el, $bad_word) !== FALSE ) {
$word_okay = false;
break;
}
}
return $word_okay;
});
I'd be inclined to use the array_filter function and change the regex to not match on word boundaries
$data1 = array('Phillyfreelance' , 'PhillyWebJobs', 'web2project', 'cleanname');
$cleanArray = array_filter($data1, function($w) {
return !preg_match('~(freelance|project|job)~i', $w);
});
Use of the preg_match() function and some regular expressions should do the trick; this is what I came up with and it worked fine on my end:
<?php
$data1=array('JoomlaFreelance','PhillyWebJobs','web2project','cleanname');
$cleanArray=array();
$badWords='/(job|freelance|project)/i';
foreach($data1 as $name) {
if(!preg_match($badWords,$name)) {
$cleanArray[]=$name;
}
}
echo(implode($cleanArray,','));
?>
Which returned:
cleanname
Personally, I would do something like this:
$badWords = ['job', 'freelance', 'project'];
$names = ['JoomlaFreelance', 'PhillyWebJobs', 'web2project', 'cleanname'];
// Escape characters with special meaning in regular expressions.
$quotedBadWords = array_map(function($word) {
return preg_quote($word, '/');
}, $badWords);
// Create the regular expression.
$badWordsRegex = implode('|', $quotedBadWords);
// Filter out any names that match the bad words.
$cleanNames = array_filter($names, function($name) use ($badWordsRegex) {
return preg_match('/' . $badWordsRegex . '/i', $name) === FALSE;
});
This should be what you want:
if (!preg_match('/(freelance|job|project)/i', $name)) {
$cleanArray[] = $name;
}

Categories