How can I make this query in Laravel:
SELECT
`p`.`id`,
`p`.`name`,
`p`.`img`,
`p`.`safe_name`,
`p`.`sku`,
`p`.`productstatusid`
FROM `products` p
WHERE `p`.`id` IN (
SELECT
`product_id`
FROM `product_category`
WHERE `category_id` IN ('223', '15')
)
AND `p`.`active`=1
I could also do this with a join, but I need this format for performance.
Consider this code:
Products::whereIn('id', function($query){
$query->select('paper_type_id')
->from(with(new ProductCategory)->getTable())
->whereIn('category_id', ['223', '15'])
->where('active', 1);
})->get();
Have a look at the advanced where clause documentation for Fluent. Here's an example of what you're trying to achieve:
DB::table('users')
->whereIn('id', function($query)
{
$query->select(DB::raw(1))
->from('orders')
->whereRaw('orders.user_id = users.id');
})
->get();
This will produce:
select * from users where id in (
select 1 from orders where orders.user_id = users.id
)
You can use variable by using keyword "use ($category_id)"
$category_id = array('223','15');
Products::whereIn('id', function($query) use ($category_id){
$query->select('paper_type_id')
->from(with(new ProductCategory)->getTable())
->whereIn('category_id', $category_id )
->where('active', 1);
})->get();
You can use Eloquent in different queries and make things easier to understand and mantain:
$productCategory = ProductCategory::whereIn('category_id', ['223', '15'])
->select('product_id'); //don't need ->get() or ->first()
and then we put all together:
Products::whereIn('id', $productCategory)
->where('active', 1)
->select('id', 'name', 'img', 'safe_name', 'sku', 'productstatusid')
->get();//runs all queries at once
This will generate the same query that you wrote in your question.
Here is my approach for Laravel 8.x gathered from multiple answers here:
Use the query builder and don't write SQL directly.
Use the models and determine everything from there. Don't use a hardcoded table name, or any name (columns, and so on) for that matter.
Product::select(['id', 'name', 'img', 'safe_name', 'sku', 'productstatusid'])
->whereIn('id', ProductCategory::select(['product_id'])
->whereIn('category_id', ['223', '15'])
)
->where('active', 1)
->get();
The script is tested in Laravel 5.x and 6.x. The static closure can improve performance in some cases.
Product::select(['id', 'name', 'img', 'safe_name', 'sku', 'productstatusid'])
->whereIn('id', static function ($query) {
$query->select(['product_id'])
->from((new ProductCategory)->getTable())
->whereIn('category_id', [15, 223]);
})
->where('active', 1)
->get();
generates the SQL
SELECT `id`, `name`, `img`, `safe_name`, `sku`, `productstatusid` FROM `products`
WHERE `id` IN (SELECT `product_id` FROM `product_category` WHERE
`category_id` IN (?, ?)) AND `active` = ?
The following code worked for me:
$result=DB::table('tablename')
->whereIn('columnName',function ($query) {
$query->select('columnName2')->from('tableName2')
->Where('columnCondition','=','valueRequired');
})
->get();
Laravel 4.2 and beyond, may use try relationship querying:-
Products::whereHas('product_category', function($query) {
$query->whereIn('category_id', ['223', '15']);
});
public function product_category() {
return $this->hasMany('product_category', 'product_id');
}
Product::from('products as p')
->join('product_category as pc','p.id','=','pc.product_id')
->select('p.*')
->where('p.active',1)
->whereIn('pc.category_id', ['223', '15'])
->get();
using a variable
$array_IN=Dev_Table::where('id',1)->select('tabl2_id')->get();
$sel_table2=Dev_Table2::WhereIn('id',$array_IN)->get();
You use DB::raw to set subquery.
Example
DB::raw('(
SELECT
`product_id`
FROM `product_category`
WHERE `category_id` IN ('223', '15') as `product_id`
')
Please try this online tool sql2builder
DB::table('products')
->whereIn('products.id',function($query) {
DB::table('product_category')
->whereIn('category_id',['223','15'])
->select('product_id');
})
->where('products.active',1)
->select('products.id','products.name','products.img','products.safe_name','products.sku','products.productstatusid')
->get();
Related
i am having this query with me which needs to be written in the eloquent form on internet not able to find exact solution for my problem.
SELECT
query_id, t1.time, result, platform_id
FROM
query_logs t1
WHERE
t1.time = (SELECT
MAX(time)
FROM
query_logs t2
WHERE
t1.query_id = t2.query_id);
i tried writing it as below i used query_Logs as model to my controller:
$bmdata = Query_Logs::select('query_id', 'time','result','platform_id')
->where('time', function($q){
$q->from('query_logs')
->selectRaw('max(time)')
->where('query_id', '=', 'query_id')
})
->get();
Can you guys help me with the same.
Use this:
$bmdata = Query_Logs::select('query_id', 'time', 'result', 'platform_id')
->where('time', function($q) {
$q->from('query_logs as t2')
->selectRaw('max(time)')
->whereColumn('t2.query_id', '=', 'query_logs.query_id');
})->get();
I have this SQL query:
SELECT *, count(*) as mostView FROM users RIGHT JOIN visitors ON users.id = visitors.user_id GROUP BY users.id HAVING users.isActive=1 AND users.fullName IS NOT NULL AND users.photo_id IS NOT NULL AND users.role_id IN(1, 3) ORDER BY mostView DESC LIMIT 5
It works, but I need convert to Laravel eloquent, i'm using laravel 5.6, could any one helpe me thanks in advance
I'm assuming that you have map the relationship in your Model if you do you can do like below,
$userViews = User::->with('vistors')
->where('isActive',1)
->whereNotNull('fullName')
->whereNotNull('photo_id')
->whereIn('role_id ',[1,3])
->get();
$mostView = $userViews->sortBy(function ($collection) {
return $collection->vistors->count()
})->take(5)
hope this helps
Not going to spoon feeding but can provide you some ideas to convert raw sql to eloquent, your sql should ideally be like this:
User::selectRaw('*', 'count(*) as mostView')
->rightJoin()
->groupBy()
->having()
->where // whereNotNull // wherIn
->orderBy()
->take(5)
->get();
Kindly refer to laravel docs: https://laravel.com/docs/5.6/queries
Thanks for all i'm studies Database: Query Builder on the link
https://laravel.com/docs/5.6/queries
and so i solved my question by myself
the answer is:
$mostViews = DB::table('users')
->rightJoin('visitors', 'users.id' , '=' , 'visitors.user_id')
->select('users.*', DB::raw('count(*) as mostView'))
->where('isActive', '=', '1')
->whereNotNull('fullName')
->where('photo_id', '<>', 'NULL')
->where(function ($q){
$q->where('role_id', '=', '1')
->orWhere('role_id', '=', '3');
})
->groupBy('user_id')
->orderBy('mostView', 'desc')->take(5)->get();
I'm using the following eloquent statement
Title::where('word', 'lovers')
->orWhere('word', 'lover')
->where('domain', $resultFromFirstKeyword->domain)
->get();
Which I can see through the SQL logger produces the following SQL
SELECT * FROM `title`
WHERE `word` = 'lovers'
OR `word` = 'lover'
AND `domain` = 'www.texasbirdlovers.com'
However the SQL that I would like to produce is
SELECT * FROM `title`
WHERE (`word` = 'lovers' OR `word` = 'lover')
AND `domain` = 'www.texasbirdlovers.com'
How would I achieve this?
This should work:
Title::whereIn('word', ['lovers', 'lover'])
->where('domain', $resultFromFirstKeyword->domain)
->get();
If, however, you want to combine them exactly like you said, try this:
Title::where(function($query) {
$query->where('word', 'lovers')
->orWhere('word', 'lover');
})
->where('domain', $resultFromFirstKeyword->domain)
->get();
Just group your query in a where clause
Title::where(function($q){
$q->where('word', 'lovers')->orWhere('word', 'lover');
})->where('domain', $resultFromFirstKeyword->domain)->get();
Try
Title::where('domain', $resultFromFirstKeyword->domain)
->where(function($query) {
return $query
->where('word', '=', 'lovers')
->orWhere('word', '=', 'word');
})->get();
Try the following:
Title::where(function($query) {
return $query
->where('word', 'lover')
->orWhere('word', 'lovers');
})
->where('domain', $resultFromFirstKeyword->domain)
->get();
I am try
ing to get something like this
select * from `users`
inner join `settings`
on `users`.`id` = `settings`.`user_id`
and NOW() NOT BETWEEN quit_hour_start AND quit_hour_end
where `notification_key` != ''
and `device_type` = 'Android'
in eloquent. Does anyone try and get success to build this query in eloquent.
I know I can use \DB::select(DB::raw()); and get my result. But I want to use ie with Laravel eloquent method.
====== update comment for tried queries========
$androidUser = User::join('settings', function ($join) {
$join->on('users.id', '=', 'settings.user_id')
->where(DB::raw("'$currentTime' NOT BETWEEN quit_hour_start AND quit_hour_end"));
})
->where('notification_key', '!=', '')
->where('device_type' ,'=', 'Android')
->get();
$users = DB::table('users')
->whereNotBetween('votes', [1, 100]) // For one column
->whereRaw("? NOT BETWEEN quit_hour_start AND quit_hour_end", [$currentTime]) // Use whereRaw for two columns
->get();
https://laravel.com/docs/5.5/queries, or you can rewrite as to wheres
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();