SELECT *
FROM table_name
WHERE
CONCAT(id,name, address) LIKE '%same_string%'
What is an alternate query for this in Laravel
Try this.
$field = ['name','id','address'];
$name = DB::Table('bookinfo')->Where(function ($query) use($string, $field) {
for ($i = 0; $i < count($field); $i++){
$query->orwhere($field, 'like', '%' . $string .'%');
}
})->get();
**
Laravel
- The general search in multiple columns the in single input
**
one of the user table in the first name, last name, job title column available and I have one input search in any value enter then find all column in associated data fetch and display
$searchQuery = trim($request->query('search'));
$requestData = ['firstname', 'lastname', 'job_title'];
$user = User::where(function($q) use($requestData, $searchQuery) {
foreach ($requestData as $field)
$q->orWhere($field, 'like', "%{$searchQuery}%");
})->get();
Try this for separate column
DB::table("table_name")->whereRaw(" (`id` like ? or `name` like ? or `address` like ? ) ",["%".$same_string."%","%".$same_string."%","%".$same_string."%"])->get();
Related
I want to iterate through list of words broken down in a function processNeedle. This is working fine with ordinary php but not in laravel.
$query = $request->input('query');
$trim = new SearchTrim();
$words = $trim->ProcessNeedle($query);
$concat = "CONCAT(";
$concat.="title,";
$concat.="'')";
$sql =DB::select("SELECT DISTINCT id,title,code,abstract FROM projects WHERE 0 ";
foreach ($words as $word) $sql.=" OR $concat LIKE '%$word%'";
$sql.=" ORDER BY id DESC";
My query function well like this in php
SQL query: SELECT DISTINCT id,title,code FROM projects WHERE 0 OR CONCAT(title,'') LIKE '%intranet%' OR CONCAT(title,'') LIKE '%mailing%' ORDER BY id DESC;
How do i achieve this in Laravel Please help
Try this example . i hope it helps you .
Pass foreach inside laravel DB::select query
$items = ['condition1', 'condition2', 'condition3'];
$results = App\Model::where(function ($query) use ($items) {
foreach($items as $item) {
$query->orWhere('dbfield', 'LIKE', "%$item%");
}
})
->get();
dd($results);
I'm trying to use multiple where queries on a sqlite database which are then only selected between two date ssDate and seDate. for some reason, I am having nothing returned when I know there is an entry in between two dates.
if($status == "newOngoingClosed"){
//dd($status, $ssDate, $seDate);
$selStatus = Account::where('cActive', '=', 'New')
->orWhere('cActive', '=', 'Ongoing')
->orWhere('cActive', '=', 'Closed')
->whereBetween ('refDate', [$ssDate, $seDate])
->get();
dd($selStatus);
return view('reports_active')->withDetails($selStatus)->withQuery($status);
}
any help would be greatly appreciated.
Instead of using multiple orWhere you can use whereIn to get the desired output:
$selStatus = Account::whereIn('cActive', ['New','Ongoing','Closed'])
->whereBetween ('refDate', [$ssDate, $seDate])
->get();
Your query currently is:
select *
from `accounts`
where `cActive` = ? or `cActive` = ? or `cActive` = ? and `refDate` between ? and ?
Notice that the last condition is and AND which means it will select things which are either new or ongoing or closed and between those dates
You need:
Account::where([
['cActive', '=', 'New','or'] ,
[ 'cActive', '=', 'Ongoing','or' ],
['cActive', '=', 'Closed','or']
])->whereBetween ('refDate', [Carbon::now(), Carbon::now()])->get() //Note the carbons are just date placeholders , you can use your own
This will execute:
select * from `accounts` where (`cActive` = ? or `cActive` = ? or `cActive` = ?) and `refDate` between ? and ?
I want to implement following SQL queries in Yii 2 but with no success.
This should give total number of unique company names:
SELECT count(DISTINCT(company_name)) FROM clients
And this should display company_name with client code and id(PK):
SELECT (DISTINCT(company_name,client_code)) FROM clients
How to achieve this?
Try this:
$total = YourModel::find()->select('company_name')->distinct()->count();
In Search Model:
public function search($params)
{
$query = YourModel::find()->select('company_name')->distinct();
// or
$query = YourModel::find()->select(['company_name', 'client_code'])->distinct();
$query->orderBy('id desc');
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
// ...
}
Answering my own question I got following working solutions:
Got the count for unique company_name:
$my = (new yii\db\Query())
->select(['company_name',])
->from('create_client')
->distinct()
->count();
echo $my;
List of distinct company_name and client_code:
$query = new yii\db\Query();
$data = $query->select(['company_name','client_code'])
->from('create_client')
->distinct()
->all();
if ($data) {
foreach ($data as $row) {
echo 'company_name: ' . $row['company_name'] . ' client_code: ' . $row['client_code'] . '<br>';
}
}
All worked fine
return Clients::find()->count('DISTINCT(company_name)');
I hope this sample is useful for you
$names = Yii::$app->db->createCommand('SELECT count(DISTINCT(company_name)) as name FROM clients')
->queryAll();
for access the the data
foreach ($names as $name){
echo $name['name'];
}
For those who need select distinct on and other columns with aliases, the following solution will work:
$modelClass::find()
->select(new Expression(
"distinct on ('col1') col1, col2, test as col3, 'hardCodeValue' as col4"
))
Note: for PGSQL it is important what quotes you put in the query.
I have to select few other columns as well instead of just top table columns. I have the code;
$records_all = DB::table('table1')
->whereExists(function($query) use ($date) {
$query->select(DB::raw(1))
->from('table2')
->whereRaw('table2.table1_id = table1.table1_id')
->whereNotExists(function($query) use ($date) {
$query->select(DB::raw(1))
->from('table3')
->whereRaw('table2.table2_id = table3.table2_id')
->whereRaw("DATE(table3.date)='" . $date . "'");
});
})
->orderBy('url')
->get();
This gives me records for table1 when required. but how to get anything from table2 or table3 ?
I am using laravel 4.2
Thanks for any help.
change DB::raw(1) to specific column you need and separate column by comma
$records_all = DB::table(DB::raw('table1, table2, table3'))
->select('table1.*','table2.table2_id','table3.table3_id')
->whereExists(function($query) use ($date) {
$query->from('table2')
->whereRaw('table2.table1_id = table1.table1_id')
->whereNotExists(function($query) use ($date) {
$query->from('table3')
->whereRaw('table2.table2_id = table3.table2_id')
->whereRaw("DATE(table3.date)='" . $date . "'");
});
})
->orderBy('url')
->get();
to get print last executed query just after above statement
$queries = DB::getQueryLog();
$last_query = end($queries);
print_r($last_query);exit;
HI I am trying to use the following and not sure how to get this fixed
SELECT * FROM search_users
WHERE
match(first_name,last_name,country,city,location,nationality,short_bio)
against (?)
AND
search_users.loc_lng BETWEEN '-0.24272918701172' AND '-0.24272918701172'
AND
search_users.loc_lat BETWEEN '51.47026338272' AND '51.47026338272'
I am trying to write a laravel query that does exactly the same as
select * from search_users
where
......
and search_users.loc_lng BETWEEN '-0.24272918701172' AND '-0.24272918701172'
AND search_users.loc_lat BETWEEN '51.47026338272' AND '51.47026338272'
If you just want to build the query / get pure data without any logic around it, you can simply use the Query Builder:
$results = DB::table('search_users')
->where('first_name', $firstname)
->where('last_name', $last_name)
->where('country', $country) //and so on
->whereBetween('loc_lng', array(-0.24272918701172, -0.24272918701172))
->whereBetween('loc_lat', array(51.47026338272, 51.47026338272))
->get();
And sure enough you can use the same syntax if you're working with a Model:
$users = User::where('key1', $value1)
->where('key2', $value2)
->whereBetween('loc_lng', array(-0.24272918701172, -0.24272918701172))
->whereBetween('loc_lat', array(51.47026338272, 51.47026338272))
->get();
A little additional explanation concerning your question about how to use AND in eloquent:
AND is used by default if you use 2 or more where()s. So
DB::table('search_users')->where('first_name', $firstname)
->where('last_name', $last_name)
equals
SELECT * FROM search_users WHERE first_name = ? AND last_name = ?
For OR you can use orWhere():
DB::table('search_users')->where('first_name', $firstname)
->orWhere('last_name', $othername)
which equals
SELECT * FROM search_users WHERE first_name = ? OR first_name = ?
And sometimes you may need something more complicated, for instance:
SELECT * FROM search_users
WHERE first_name = ?
AND (last_name = ? OR last_name = ?)
AND age > 27
In Eloquent, this would be:
DB::table('search_users')
->where('first_name', $firstname)
->where(function($query) {
$query->where('last_name', $lastName1);
$query->orWhere('last_name', $lastName2);
})
->where('age', '>', 27)