Translate raw complex SQL query into Eloquent - php

Can anyone help me translate this into Eloquent?
select * from resources
left join links
on links.resource_id = resources.id
and (links.ud_id IS NULL OR links.ud_id = '7')
where resources.user_id = '1'
and resources.subject_id = '4'
Thank you in advance

This should do the trick:
DB::table('resources')
->leftJoin('links', function($join) {
$join->on('links.resource_id', '=', 'resources.id');
$join->where(function($query) {
$query->whereNull('links.ud_id');
$query->orWhere('links.ud_id', '=', 7);
});
})
->where('user_id', 1)
->where('subject_id', 4)
->get();

Related

Helpe me to convert SQL query to Laravel eloquent

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();

How to use where not between in Laravel 5.5?

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

How to write union query in Laravel?

I'm using laravel 5.0 and I have mysql query:
SELECT surat_masuk.id_surat,
surat_masuk.nomor_surat
FROM surat_masuk
WHERE ! EXISTS (SELECT *
FROM file_replace
WHERE id_surat_lama = surat_masuk.id_surat)
AND surat_masuk.id_jenis_surat = '6'
AND surat_masuk.deleted = '0'
UNION
SELECT id_surat_lama
FROM file_replace
WHERE id_surat_baru = '38'
And I write that in my laravel code into:
$nomor_surat1 = DB::table('surat_masuk')->select('id_surat', 'nomor_surat')
->where('id_jenis_surat', '=', $id_jenis_surat)
->where(function ($query) {
$query->where('masa_berlaku_to', '>=', date('Y-m-d'))
->orwhere('masa_berlaku_to', '=', '0000-00-00');
})
->whereExists(function ($query) {
$query
->from('file_replace')
->where('id_surat_lama', '==', 'surat_masuk.id_surat');
})
->where('deleted', '=', '0');
$nomor_surat = DB::table('file_replace')->join('surat_masuk', 'file_replace.id_surat_lama', '=', 'surat_masuk.id_surat')
->select('id_surat_lama', 'nomor_surat')
->where('id_surat_baru', '=', $id_surat_baru)
->union($nomor_surat1)->get();
But I've got nothing showed. Do you know where is the mistakes?
Well, I finally using raw query..
$results = DB::select( DB::raw("SELECT * FROM some_table WHERE some_col = '$someVariable'") );
Please see the answer, that might help you..
SELECT surat_masuk.id_surat,
surat_masuk.nomor_surat
FROM surat_masuk
WHERE ! EXISTS (SELECT *
FROM file_replace
WHERE id_surat_lama = surat_masuk.id_surat)
AND surat_masuk.id_jenis_surat = '6'
AND surat_masuk.deleted = '0'
UNION
SELECT id_surat_lama
FROM file_replace
WHERE id_surat_baru = '38'
//converted to laravel elequent query.
$first_sql=DB::table('surat_masuk as sm1')
->whereNotExists(function($query) {
$query->from('file_replace as fr1')
->where('fr1.id_surat_lama','sm1.id_surat');
})->where('sm1.id_jenis_surat',6)
->where('sm1.deleted',0)
->select('sm1.id_surat', 'sm1.nomor_surat' );
//will return an elequent object, append '->get()' to see the output seperately
$actual_result=DB::table('file_replace as fr2')
->where('fr2.id_surat_baru',38)
->select('fr2.id_surat_lama')
->union($first_sql)
->get();
//will return an array of result set

Laravel 4 Query Builder SQL Statement

Good day, I have this SQL statement and I'm having a difficulty on how to convert this in Laravel Query.
I read the docs in http://laravel.com/docs/4.2/queries and I'm confused. Any help would do.
SELECT count(*) FROM `transactions` WHERE `borrower_id` = 2
AND `book_id` = 2 AND (
(
`reservedDate` IS NOT NULL
and `borrowedDate` IS NULL
)
OR (
`borrowedDate` IS NOT NULL
AND `returnedDate` IS NULL
)
)
So I try to build this query by reading the documentations from Laravel. Still haven't tested it yet but hope it could give you the right direction.
Maybe next time, you should show your own query (it's ok if it's not correct). It's easier to get start from there.
$super_query = DB::table('transactions')->where('borrower_id' , '=' , 2)->where('book_id', '=' , 2)->where( function ( $query ) {
$query->where(function ($query1) {
$query1->whereNotNull('reservedDate')->whereNull('borrowedDate')
)->orWhere(function ($query2) {
$query2->whereNotNUll('borrowedDate')->whereNull('returnedDate')
})
})->count();
DB::table('transactions')
->Where('borrower_id', '=', 2)
->Where('book_id', '=', 2)
->where(function($query)
{
$query->where(function($query1) {
$query1->whereNotNull('reservedDate')
->whereNull('borrowedDate');
})
->orWhere(function($query2) {
$query2->whereNotNull('borrowedDate')
->whereNull('returnedDate');
});
})->count();
try this.. this will result into
select count(*) from `transactions` where `borrower_id` = 2 and `book_id` = 2 and ((`reservedDate` is not null and `borrowedDate` is null) or (`borrowedDate` is not null and `returnedDate` is null))
Try this:
Eloquent
Transactions::where('borrower_id', '=', 2)
->where('book_id', '=', 2)
->where(function($query)
{
$query->whereNotNull('reservedDate')
->whereNull('borrowedDate');
})
->orWhere(function($query)
{
$query->whereNotNull('borrowedDate')
->whereNull('returnedDate');
})
->count();
book::count()->where('borrower_id','=','2','book_id','=',2)

How to do this in Laravel, subquery where in

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();

Categories