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);
Related
I want to sort multiple columns in Laravel 4 by using the method orderBy() in Laravel Eloquent. The query will be generated using Eloquent like this:
SELECT *
FROM mytable
ORDER BY
coloumn1 DESC, coloumn2 ASC
How can I do this?
Simply invoke orderBy() as many times as you need it. For instance:
User::orderBy('name', 'DESC')
->orderBy('email', 'ASC')
->get();
Produces the following query:
SELECT * FROM `users` ORDER BY `name` DESC, `email` ASC
You can do as #rmobis has specified in his answer, [Adding something more into it]
Using order by twice:
MyTable::orderBy('coloumn1', 'DESC')
->orderBy('coloumn2', 'ASC')
->get();
and the second way to do it is,
Using raw order by:
MyTable::orderByRaw("coloumn1 DESC, coloumn2 ASC");
->get();
Both will produce same query as follow,
SELECT * FROM `my_tables` ORDER BY `coloumn1` DESC, `coloumn2` ASC
As #rmobis specified in comment of first answer you can pass like an array to order by column like this,
$myTable->orders = array(
array('column' => 'coloumn1', 'direction' => 'desc'),
array('column' => 'coloumn2', 'direction' => 'asc')
);
one more way to do it is iterate in loop,
$query = DB::table('my_tables');
foreach ($request->get('order_by_columns') as $column => $direction) {
$query->orderBy($column, $direction);
}
$results = $query->get();
Hope it helps :)
Use order by like this:
return User::orderBy('name', 'DESC')
->orderBy('surname', 'DESC')
->orderBy('email', 'DESC')
...
->get();
Here's another dodge that I came up with for my base repository class where I needed to order by an arbitrary number of columns:
public function findAll(array $where = [], array $with = [], array $orderBy = [], int $limit = 10)
{
$result = $this->model->with($with);
$dataSet = $result->where($where)
// Conditionally use $orderBy if not empty
->when(!empty($orderBy), function ($query) use ($orderBy) {
// Break $orderBy into pairs
$pairs = array_chunk($orderBy, 2);
// Iterate over the pairs
foreach ($pairs as $pair) {
// Use the 'splat' to turn the pair into two arguments
$query->orderBy(...$pair);
}
})
->paginate($limit)
->appends(Input::except('page'));
return $dataSet;
}
Now, you can make your call like this:
$allUsers = $userRepository->findAll([], [], ['name', 'DESC', 'email', 'ASC'], 100);
$this->data['user_posts'] = User_posts::with(['likes', 'comments' => function($query) { $query->orderBy('created_at', 'DESC'); }])->where('status', 1)->orderBy('created_at', 'DESC')->get();
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();
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 this Laravel 4.2 Eloquent Query
$m[] = Auth::user()->id;
foreach ($friends as $friend) {
$m[] = $friend->added_user;
}
$news = NewsFeed::whereIN('user_id', $m )->take($limit)->skip($offset)->get();
Actual query:
$news = NewsFeed::whereIN('user_id', array( 'CUS_6367VkCX5i243656TwM3', 'CUS_G530t786S1GVwlcJ3Nw1', 'CUS_xks5oi3dy2C0sa02usD2' ) )->take(10)->skip(5)->get();
Database:
It should return something, Newsfeed Table has datas in it but
result is none, its empty.
What is wrong with my Laravel 4.2 Eloquent Query?
BUT WHEN I DO THIS:
$news = NewsFeed::whereIN('user_id', $m )->get();
it returns a result, without limit and skip.
It seems that $m[] = $friend->added_user; is where you go wrong
dd($friend->added_user)
You will see in your array $m objects of users. However, in your query what's needed is the user_id of added_user.
In this case, you should modify as follows:
$m[] = $friend->added_user()->first()->user_id; //it depends on what your added_user returns, if it returns an array, you should loop over it to get all ids or use ->lists('user_id') to get an array of user_id
Hope it helps
This will do the trick:
$news = DB::select( DB::raw(" SELECT * FROM `news_feed` WHERE `user_id` IN ('CUS_6367VkCX5i243656TwM3', 'CUS_G530t786S1GVwlcJ3Nw1', 'CUS_xks5oi3dy2C0sa02usD2') LIMIT 5, 5 ") );
I want to sort multiple columns in Laravel 4 by using the method orderBy() in Laravel Eloquent. The query will be generated using Eloquent like this:
SELECT *
FROM mytable
ORDER BY
coloumn1 DESC, coloumn2 ASC
How can I do this?
Simply invoke orderBy() as many times as you need it. For instance:
User::orderBy('name', 'DESC')
->orderBy('email', 'ASC')
->get();
Produces the following query:
SELECT * FROM `users` ORDER BY `name` DESC, `email` ASC
You can do as #rmobis has specified in his answer, [Adding something more into it]
Using order by twice:
MyTable::orderBy('coloumn1', 'DESC')
->orderBy('coloumn2', 'ASC')
->get();
and the second way to do it is,
Using raw order by:
MyTable::orderByRaw("coloumn1 DESC, coloumn2 ASC");
->get();
Both will produce same query as follow,
SELECT * FROM `my_tables` ORDER BY `coloumn1` DESC, `coloumn2` ASC
As #rmobis specified in comment of first answer you can pass like an array to order by column like this,
$myTable->orders = array(
array('column' => 'coloumn1', 'direction' => 'desc'),
array('column' => 'coloumn2', 'direction' => 'asc')
);
one more way to do it is iterate in loop,
$query = DB::table('my_tables');
foreach ($request->get('order_by_columns') as $column => $direction) {
$query->orderBy($column, $direction);
}
$results = $query->get();
Hope it helps :)
Use order by like this:
return User::orderBy('name', 'DESC')
->orderBy('surname', 'DESC')
->orderBy('email', 'DESC')
...
->get();
Here's another dodge that I came up with for my base repository class where I needed to order by an arbitrary number of columns:
public function findAll(array $where = [], array $with = [], array $orderBy = [], int $limit = 10)
{
$result = $this->model->with($with);
$dataSet = $result->where($where)
// Conditionally use $orderBy if not empty
->when(!empty($orderBy), function ($query) use ($orderBy) {
// Break $orderBy into pairs
$pairs = array_chunk($orderBy, 2);
// Iterate over the pairs
foreach ($pairs as $pair) {
// Use the 'splat' to turn the pair into two arguments
$query->orderBy(...$pair);
}
})
->paginate($limit)
->appends(Input::except('page'));
return $dataSet;
}
Now, you can make your call like this:
$allUsers = $userRepository->findAll([], [], ['name', 'DESC', 'email', 'ASC'], 100);
$this->data['user_posts'] = User_posts::with(['likes', 'comments' => function($query) { $query->orderBy('created_at', 'DESC'); }])->where('status', 1)->orderBy('created_at', 'DESC')->get();