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;
Related
I get the problem when I try looping the data to store in variable for making the pie chart on Laravel
this is my code in controller
// $countUser = DB::select(DB::raw("
// SELECT r.name AS name, count(u.id) AS countUser
// FROM users u, role_user ru, roles r
// WHERE u.id = ru.user_id
// AND ru.role_id = r.id
// GROUP BY name "));
$countUser = DB::table(DB::raw('users'))
->select(DB::raw('roles.name AS name, count(users.id) AS countUser'))
->join('role_user', 'users.id', '=', 'role_user.user_id')
->join('roles', 'role_user.role_id', '=', 'roles.id')
->groupByRaw('role_user.role_id, name')->get();
$data = " ";
foreach($countUser as $user){
$data = "['".$user->name."', ".$user->countUser."],";
}
dd($data);
I expect the result like this
but, I get the result only one
When I try this dd($countUser);. This is the result
How to fix it?
In your example you keep overwriting $data, instead lets use Laravel Collection methods to help you.
Map all your entries to the format [$name, $count]. Then use the Collection method implode(), to join the strings with a comma.
$concatenatedUsers = $countUser->map(function ($user) {
return '[' . $user->name . ', ' . $user->countUser ']';
})->implode(', ');
dd($concatenatedUsers);
(select business_name from clients where id = orders.main_client_id) as b_name
This above sql query and I am converted sql to laravel type is right or wrong because this below query give me output [][][] this type any suggestion..
->addColumn('business_name', function($data) {
$b_name = DB::table("clients")
->select("business_name")
->where('clients.id','main_client_id')
->get();
return $b_name;
});
You left out the comparison symbol (=)
$b_name = DB::table('clients')
->where('id', '=', 'main_client_id')
->get();
or
$b_name = DB::table('clients')
->where('clients.id', '=', 'main_client_id')
->value('business_name');
you are comparing with column value not mere value, so you have to use whereColumn:
->addColumn('business_name', function($data) {
$b_name = DB::table("clients")
->select("business_name")
->whereColumn('clients.id','main_client_id')
->get();
return $b_name;
});
I need help for query in laravel
My Custom Query: (Return Correct Result)
Select * FROM events WHERE status = 0 AND (type="public" or type = "private")
how to write this query in Laravel.
Event::where('status' , 0)->where("type" , "private")->orWhere('type' , "public")->get();
But it's returning all public events that status is not 0 as well.
I am using Laravel 5.4
Pass closure into the where():
Event::where('status' , 0)
->where(function($q) {
$q->where('type', 'private')
->orWhere('type', 'public');
})
->get();
https://laravel.com/docs/5.4/queries#parameter-grouping
In your case you can just rewrite the query...
select * FROM `events` WHERE `status` = 0 AND `type` IN ("public", "private");
And with Eloquent:
$events = Event::where('status', 0)
->whereIn('type', ['public', 'private'])
->get();
When you want to have a grouped OR/AND, use a closure:
$events = Event::where('status', 0)
->where(function($query) {
$query->where('type', 'public')
->orWhere('type', 'private');
})->get();
Use this
$event = Event::where('status' , 0);
$event = $event->where("type" , "private")->orWhere('type' , "public")->get();
or this
Event::where('status' , 0)
->where(function($result) {
$result->where("type" , "private")
->orWhere('type' , "public");
})
->get();
Try this. It works for me.
$rand_word=Session::get('rand_word');
$questions =DB::table('questions')
->where('word_id',$rand_word)
->where('lesson_id',$lesson_id)
->whereIn('type', ['sel_voice', 'listening'])
->get();
$filter = [];
$filter[] = "type="public" or type = "private"";
$filter[] = "status = 0";
$event = Event::whereRaw(implode(' AND ',$filter))->get();
You can store all condition in filter array and then apply to query
below is my query . i want to get all results If (nic or mobile) and course matches ,
please advice
$conversations = Inquiries::whereRaw("( `course` = $request->input('course'))
AND( `mobile` = $request->input('mobile') OR 'nic', 'LIKE', '%'.$request->input('nic').'%')")
->get();
You need to properly create a query, like this:
$conversations = Inquiries::where('course', '=', $request->input('course'))
->where(function($query) use ($request) {
$query->where('mobile','=', $request->input('mobile'))
->orWhere('nic','LIKE','%'.$request->input('nic').'%');
})
->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.