How to get Laravel Eloquent Count and Case in Join - sql

Good day!
I am having a problem trying a query in my laravel 8 project. In my database, I have 2 tables: users and roles. In users table it has an roles column which is the data inserting in that column is the roles table id.
Or can any one help me to convert this sql command into laravel.
----SQL----
SELECT roles.id, roles.role_name,
COUNT(users.roles) AS users,
roles.permission,
case when roles.`status` = 1 then 'Active'
ELSE 'Inactive'
END AS `status`
FROM roles
INNER JOIN users ON roles.id = users.roles
GROUP BY roles.id
--My laravel code that is not working--
$data = Roles::select(
"roles.id",
"roles.role_name",
DB::raw("count(users.roles) as users, roles.permission, (CASE WHEN roles.status = 1 THEN 'Active' ELSE 'Inactive' END) as status")
)
->join("users", "users.roles","=","roles.id")
->groupBy("roles.id")
->get();
Somebody help me. Thanks

DB::table("roles")
->innerJoin("users", function($join){
$join->on("roles.id", "=", "users.roles");
})
->select("roles.id", "roles.role_name", "count (users.roles) as users", "roles.permission")
->addSelect(DB::raw("case when roles.`status` = 1 then 'active' else 'inactive' end as `status`"))
->groupBy("roles")
->get();

Change the model name i.e Role as per whatever your model name is ex: Roles
$data = Role::select([
"roles.id",
"roles.name",
DB::raw("count(users.roles) as users, roles.permission, (CASE WHEN roles.status = 1 THEN 'Active' ELSE 'Inactive' END) as status")
])
->innerJoin("users", function($join){
$join->on("roles.id", "=", "users.roles");
})
->groupBy("roles.id")
->get();

I already know what is cause. First, I can't identify the error because I am using dataTable so the error is from dataTable. Then I tried to fetch the result of my query using view and the error says SQLSTATE[42000]: Syntax error or access violation: 1055
This the solution I deed. Kindly see below:
In config\database.php
Find mysql array and change the 'strict' => true to 'strict' => false
Thank you for help guys.

Related

How to create active record query in rails?

I'm new in rails and I have a sql query but I don't know how can I convert it into rails active records query.
UserExercise.connection.exec_query("SELECT * FROM (SELECT \"user_courses_progresses\".\"user_id\", \"user_courses_progresses\".\"progress\" FROM \"user_courses_progresses\" WHERE \"user_courses_progresses\".\"is_primary\" IS TRUE) x JOIN users ON \"x\".\"user_id\" = \"users\".\"id\" ORDER BY progress desc")
Combining Active Record and "raw" SQL that might look like this:
User
.select('*')
.from(
UserCoursesProgress
.select(:user_id, :progress)
.where(is_primary: true),
:x
)
.joins('JOIN users ON x.user_id = users.id')
.order(progress: :desc)

SQL Postgre to show 1 data if get same some multiple data and how to implement to laravel query

i want to ask about sql in postgresql, i got data from join with 3 table, i got the result but i got multiple data like this image
result
and here my sql code in postgresql
select users.* from users inner join model_has_roles on model_has_roles.model_id = users.id
left join roles on roles.id = model_has_roles.role_id where roles.name not in ('job-seeker') order by users.name asc
how to fix this query where i got the multiple data only 1 data to show.
and i want this sql to implement to laravel query and here my code now
public function getAccountList(){
$req = app(Request::class);
// $getAccount = User::query();
$getAccount = User::join('model_has_roles', function($join) {
$join->on('users.id', '=', 'model_has_roles.model_id');
})->leftJoin('roles', function($join){
$join->on('model_has_roles.role_id', '=', 'roles.id');
});
$getAccount->whereNotIn('roles.name', ['job-seeker']);
if ($q = $req->query('q')) {
$searchTerm = trim(strtolower($q));
$getAccount->whereRaw(
'LOWER(users.name) like (?) or LOWER(users.email) like (?)',
["%{$searchTerm}%", "%{$searchTerm}%"]
);
}
// $getAccount->get()->unique('name');
$getAccount->select(['users.*']);
$paginator = $this->pagination($getAccount);
return $this->paginate($paginator, new UserTransformer);
}
how to fix the query only 1 data to show not the multiple same data. thank you for helping me. God Bless You
use distinct()
$data = DB::table('test')->[your query builder]->distinct()->get();
Laravel Query Builder Docs
Just change a bit to make it related to your query builder

Add multiple rows in Laravel DB Query (for migrating WordPress usermeta table into new Laravel table)

I'm migrating Users from WordPress to Laravel. I want to join the users and user_meta tables. Then I will import into a new table.
In my user_meta table I have multiple rows assigned to the user_id. How do I import multiple rows with their own unique identifier.
Eg.
umeta_id = 1, user_id = 1, meta_key = first_name, meta_value = Bob
umeta_id = 2, user_id = 1, meta_key = last_name, meta_value = Builder
In the above example, I'd like to add first_name and last_name to the query output.
Then import into a new column in the Laravel DB (and stop using the user_meta reference table approach WordPress uses).
Here is my current query code and the output I get:
$wp_users = DB::connection('wordpress_db')
// ->select(DB::raw('um.meta_value as first_name'))
->select('um.meta_value as first_name')
->table('wp_users')
->leftJoin('wp_usermeta as um', function ($q) {
$q->on('um.user_id', '=', 'wp_users.id')
->where('um.meta_key', '=', "first_name");
})
->orderBy('wp_users.id');
and if i dump the output:
+"ID": 1
+"user_login": "123"
+"user_pass": "123"
+"user_nicename": "123"
+"user_email": "b#x"
+"user_url": "https://x"
+"user_registered": "2016-1-1 13:47:32"
+"user_activation_key": ""
+"user_status": 0
+"display_name": "Bobby Builds"
+"umeta_id": 222
+"user_id": 1
+"meta_key": "first_name"
+"meta_value": "Bob"
Rather than meta_value and meta_key I just want 'first_name' => 'bob' and then also the ability to do this for multiple values in the user_meta reference table
If I was writing RAW sql then I think I would approach this by having a left_join per value I want to get. I would then create an alias like
SELECT um1.meta_value as first_name
SELECT um2.meta_value as last_name
LEFTJOIN wp_usermeta as um1
LEFTJOIN wp_usermeta as um2
I've noodled around without luck - any ideas appreciated.
Thanks!
I've written about some of the processes involved here for further reference: http://raison.co/migrating-wordpress-users-to-laravel/
I did this in the end by using select to choose all columns from wp_users and then selectively adding the new joins.
See the code fixed code below:
$wp_users = DB::connection('wp_db')
->table('wp_users')
->leftJoin('wp_usermeta as um', function ($q) {
$q->on('um.user_id', '=', 'wp_users.id')
->where('um.meta_key', '=', "wbp_user_mob_phone");
})
->leftJoin('wp_usermeta as um2', function ($q) {
$q->on('um2.user_id', '=', 'wp_users.id')
->where('um2.meta_key', '=', "first_name");
})
->select('wp_users.*', 'um.meta_value as wbp_user_mob_phone', 'um2.meta_value as first_name')
->orderBy('wp_users.id');

Write Nested Select Query in Laravel 5.3

How do I write a complex query in Laravel 5.3? I am trying but not getting the result I expect.
Query
SELECT * FROM (SELECT posts.post_id
FROM posts
WHERE ((posts.user_id = 1 AND posts.user_type = 'user')
OR (posts.user_id IN (1) AND posts.user_type = 'page'))) posts
WHERE posts.post_id > '0' ORDER BY posts.post_id DESC
Please help me write this using Laravel Query Builder.
#Punit Gajjar has provided one solution, but that's not quite what your question was given the terms Query Builder. His solution will work, but half it it doesn't make use of the query builder (it's just a copy/paste and throwing your SQL into a raw query, which is essentially exactly the same thing as you had before) and therefore I feel it's necessary to provide you with an additional option:
Post::where('post_id', '>', 0)
->where(function($query) {
$query->where(function($subquery) {
$subquery->where('user_id', 1)->where('user_type', 'user');
})->orWhere(function($subquery) {
$subquery->whereIn('user_id', [1])->where('user_type', 'page');
});
})
->orderBy('post_id', 'DESC')
->get();
I've kept variables names short just for readability purposes, but the argument in the anonymous functions ($query and $subquery) are the query builder instances.
Here is your answer .
$MyQuery = DB::table(DB::Raw("(SELECT
posts.post_id
FROM
posts
WHERE
(
(
posts.user_id = 1
AND posts.user_type = 'user'
)
OR
(
posts.user_id IN (1)
AND posts.user_type = 'page'
)
)
)"))
->where('posts.post_id','>',"0")->orderBy("posts.post_id" , "DESC")->get();
Try printing query once using ->toSql() like this
echo $MyQuery = DB::table(DB::Raw("(SELECT
posts.post_id
FROM
posts
WHERE((
posts.user_id = 1
AND posts.user_type = 'user'
)
OR(
posts.user_id IN (1)
AND posts.user_type = 'page'
)))"))
->where('posts.post_id','>',"0")->orderBy("posts.post_id" , "DESC")->toSql();
die();

Expression type 'NhSumExpression' is not supported by this SelectClauseVisitor

I have a query that I can run in LinqPad, but not in NHibernate LINQ. I found a similar bug on NHibernate Jira NHibernate NH-2865, but I think this perhaps a different bug and I'm looking for possible alternatives.
The query that works in LinqPad using default LINQ to SQL is like this:
from ticket in LotteryTickets
group tiket by ticket.ticketType into g
select new
{
TicketType = g.Key,
TotalWinningTickets = g.Count(b => b.WinAmount != 0),
TotalWon = g.Sum(b => b.WinAmount * b.ticketWeight),
TotalTickets = g.Count(),
}
There are various other ways to count the TotalWinningTickets such as TotalWinningTickets = g.Sum(t => t.WinAmount > 0 ? 1 : 0) or g.Sum(t => t.WinAmount == 0 ? 0 : 1)
Now, with NHibernate LINQ I have been unable to get this working without changing my underlying db table. My alternative was to add a table column called HasWon and I set it to 0 for false and 1 for true. This does work, but I'm left feeling there is a better way other than modifying the db table. Perhaps a subselect using a calculated field. My NHibernate LINQ ended up looking like this:
from ticket in session.Query<Ticket>()
group ticket by ticket.TicketType into g
select new ReportRow
{
TicketType = g.Key,
TotalWinningBets = g.Sum(t => t.HasWon),
TotalTickets = g.Count(),
TotalWon = g.Sum(t => t.WinAmount * t.WagerWeight)
};
What I'm effectively trying to do is multiple Select COUNT in my NHibernate query, but based on different criteria. The strangest this is that NHibernate converts all my Count(t => t.???) incorrectly into COUNT(*) in the generated SQL.
LinqPad generates SQL that works this way:
SELECT SUM(
(CASE
WHEN [t1].[WinAmount] > #p3 THEN #p4
ELSE #p5
END)) AS [value]
Hoping there is a better way.