I use laravel eloquent outside laravel.
I have a query that is supposed to get only posts that are featured (featured field = 1) and of any of the 3 types (blog, forum and page).
$latestFeaturedPosts = $db->table( 'posts' )
->where( 'featured', '=', 1 )
->orWhere( 'post_type', '=', 'blog' )
->orWhere( 'post_type', '=', 'forum' )
->orWhere( 'post_type', '=', 'page' )
->limit( 15 )
->orderBy( 'created_at', 'desc' )
->get()->toArray();
I expected this query to return what I wanted, but it does return also posts where featuredcolumn is not 1.
Why ? How should I modify this syntax to enforce this ?
I do not now this language, but will give you a starting point to look into.
Your query will be expanded to:
SELECT * FROM posts where featured = 1 OR post_type = 'blog' OR post_type = 'forum' OR post_type = 'page' LIMIT 15 ORDER BY created_at DESC;
In this query, any row that matches any one of the 4 criteria will be returned.
For you to get the results you expect, your query needs to be evaluated to:
SELECT * FROM posts where featured = 1 AND ( post_type = 'blog' OR post_type = 'forum' OR post_type = 'page' ) LIMIT 15 ORDER BY created_at DESC;
In this example, we will always enforce the featured type, and then can select any 3 types that are also featured.
How to do this in your language, I am not sure.
This will work for you:
$db->table('posts')
->where('featured', 1)
->whereIn('post_type', ['blog', 'forum', 'page'])
->limit(15)
->orderBy('created_at', 'desc')
->get()->toArray();
Your query doesn't work as expected because you're using orWhere() without a closure which would group orWhere() clauses.
Related
I want to fetch data from database which has booking year is 2022, and the column I have is tanggal_take whose value format is 'Y-m-d', so I want to use SELECT * FROM table_name WHERE YEAR(tanggal_take) = "2022"; How to write it in laravel controller using Eloquent?
here is my code now
$data = Booking::join('users', 'users.id', '=', 'bookings.id_member')
->join('packages', 'packages.kode_paket', '=', 'bookings.kode_paket')
->where( DB::raw('YEAR(bookings.tanggal_take)'), '=', $request->range )
->get(['bookings.*', 'packages.*', 'users.*']);
The result is 0 but in database i have 4 datas with year 2022. I also already change ->where( DB::raw('YEAR(bookings.tanggal_take)'), '=', $request->range ) to ->whereYear('bookings.tanggal_take', '=', $request->range ) but still 0 result. Any hint? I will also looking for documentation by my self rn. Thanks
i has raw query in laravel like this
public function getPopularBook(){
$book = DB::select("
with totalReview as(
SELECT r.book_id , count(r.id)
FROM review r
GROUP BY r.book_id
)
SELECT *
from totalReview x
left JOIN (
SELECT b.*,
case when ((now() >= d.discount_start_date and now() <= d.discount_end_date) or (now() >= d.discount_start_date and d.discount_end_date is null)) then (b.book_price-d.discount_price)
ELSE b.book_price
end as final_price
FROM discount d
right JOIN book b
on d.book_id = b.id
) as y
on x.book_id = y.id
ORDER BY x.count DESC, y.final_price ASC
LIMIT 8"
);
return $book;
}
so when i want to return a paginate, it doesn't work so can i convert this to query build to use paginate
This is a very un-optimized raw query in itself. You are performing too many Join in Subquery just to sort by price
i'm assuming the database table:
books[ id, name, price ]
reviews[ id, book_id ]
discounts[ id, book_id, start_date, end_date, discount_price]
Look how easy it is if you just use Eloquent:
Book::withCount('reviews')->orderBy('reviews_count')->get();
this will give you all the Books order by number of reviews
now with the final price, this can be a bit tricky, let's take a look at a query when we don't consider discount time
Book::withCount('reviews')
->withSum('discounts', 'discount_price') //i'm assuming a book can have many discount at the same time, so i just sum them all
->addSelect(
DB::raw('final_price AS (books.price - discounts_sum_discount_price)')
)
->orderBy('reviews_count', 'asc') // =you can specify ascending or descending
->orderBy('final_price', 'desc') //in laravel chaining multiple orderBy to order multiple column
->get();
I dont even need to use Subquery!! But how do we actually only add the "active" discount?, just need to modify the withSum a bit:
Book::withCount('reviews')
->withSum(
[
'discounts' => function($query) {
$query->where('start_date', '<=', Carbon::now())
->where('end_date', '>=', Carbon::now())
}
],
'discount_price'
)
->addSelect(
DB::raw('final_price AS (books.price - discounts_sum_discount_price)')
)
->orderBy('reviews_count', 'asc') // =you can specify ascending or descending
->orderBy('final_price', 'desc') //in laravel chaining multiple orderBy to order multiple column
->get();
and it is done
What about pagination? just replace the get() method with paginate():
Book::withCount('reviews')
->withSum(['discounts' => function($query) {
$query->where('start_date', '<=', Carbon::now())->where('end_date', '>=', Carbon::now())
}],'discount_price')
->addSelect(DB::raw('final_price AS (books.price - discounts_sum_discount_price)')) //just format to be a bit cleaner, nothing had changed
->orderBy('reviews_count', 'asc')
->orderBy('final_price', 'desc')
->paginate(10); //10 books per page
WARNING: this is written with ELoquent ORM, not QueryBuilder, so you must define your relationship first
I tried this in laravel, but it's not working. I can't get it to work it's working when I use it straight on PHPMyAdmin
SELECT service,
count(*) as total_count,
sum(if(status ='Successful',1,0)) as successful_count,
sum(if(status ='Failed',1,0)) as failed_count
FROM `wallet_ledgers`
WHERE operator = "-"
AND user_id = 5
group by service
this is the desired output The way the table should look
You can use DB::raw
Link: Laravel-raw-expressions
$result = DB::table('wallet_ledgers')
->select(DB::raw("service, count(*) as total_count, sum(if(status ='Successful',1,0)) as successful_count, sum(if(status ='Failed',1,0)) as failed_count"))
->where([
[ 'operator', '=', '-'],
['user_id', '=', '5'],
])
->groupBy('service')
->get();
I've created MySQL query for searching results. The query works properly but if I use laravel pagination on this query I get an error
Call to a member function paginate() on array ,
How to solve this with pagination?
$search = \DB::SELECT("SELECT l.*,
r.id AS reservation_id,
r.status AS res_status,
r.start_date,
r.end_date,
Avg(r.rating) AS rating
FROM listings l
LEFT JOIN reservations r ON r.listing_id = l.id
WHERE ( ( Cast('" . $search_date . "' AS date) NOT BETWEEN r.start_date AND r.end_date ) OR r.status = 'Cancel' )
AND l.city_id = $city_id
AND l.persons >= $guests
AND l.listing_type_id = $type
GROUP BY l.id
ORDER BY r.rating DESC
");
DB::select() will return an array. You could probably convert your query to a Query Builder and then use paginate() on it. For example:
$search = DB::table('listings')
->selectRaw('listings.*, reservations.id AS reservation_id, reservations.status AS res_status, reservations.start_date, reservations.end_date, AVG(reservations.rating) as rating')
->leftJoin('reservations', 'reservations.listing_id', 'listings.id')
->whereRaw("(CAST(? AS date) NOT BETWEEN reservations.start_date AND reservations.end_date) or reservations.status = 'Cancel'", [$search_date])
->where('listings.city_id', '=', $city_id)
->where('listings.persons', '>=', $guests)
->where('listings.listing_type_id', '=', $type)
->groupBy('listings.id')
->orderBy('reservations.rating', 'DESC')
->paginate(10);
I know that something similar was here some time ago,but it wasn't the same case and I can't just figure it out on myself.
I need to transform raw SQL query to Eloquent.
This query contains SELECT COUNT in WHERE clause, for simplicity I have this (may has not much sense) query :
SELECT u.column1, u.column2, u.column3, s.column1 FROM users u
LEFT JOIN salary s ON u.id = s.user_id
WHERE
(
SELECT count(cars_id) FROM cars WHERE cars.user_id = u.id
) = 0
AND u.city IN ("London","Paris")
I tried:
$columns = [
'users.column1',
'users.column2',
'users.column3',
'salary.column1'
];
$q = User::select($columns)
->leftJoin('salary', 'salary.user_id', '=', 'users.id')
->whereRaw(" (SELECT COUNT(cars_id) FROM cars WHERE cars.user_id = u.id) = 0 ")
->whereRaw("u.city IN ('London','Paris')")
->get();
But it doesn't return same results as raw SQL (SQL had 161 rows and Eloquent 154 rows).
Maybe you know how to transform this kind of query correctly to Eloquent?
Thanks
Based on your query I believe this should do it:
DB::table('users as u')
->select([ 'u.column1', 'u.column2', 'u.column3', 's.column1'])
->leftJoin('salary as s', 'u.id', '=', 's.user_id')
->leftJoin('cars as c', 'c.user_id', '=', 'u.id')
->whereIn('u.city', ['London', 'Paris'])
->havingRaw('count(c.id) = 0')
->get();
Please let me know.