Laravel 4 Query Builder SQL Statement - php

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)

Related

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

Translate raw complex SQL query into Eloquent

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

convert SQL query to query builder style

Im trying days to understand how I can convert a SQL query to a query builder style in laravel.
My SQL query is:
$tagid = Db::select("SELECT `id` FROM `wouter_blog_tags` WHERE `slug` = '".$this->param('slug')."'");
$blog = Db::select("SELECT *
FROM `wouter_blog_posts`
WHERE `published` IS NOT NULL
AND `published` = '1'
AND `published_at` IS NOT NULL
AND `published_at` < NOW()
AND (
SELECT count( * )
FROM `wouter_blog_tags`
INNER JOIN `wouter_blog_posts_tags` ON `wouter_blog_tags`.`id` = `wouter_blog_posts_tags`.`tags_id`
WHERE `wouter_blog_posts_tags`.`post_id` = `wouter_blog_posts`.`id`
AND `id`
IN (
'".$tagid[0]->id."'
)) >=1
ORDER BY `published_at` DESC
LIMIT 10
OFFSET 0");
Where I now end up to convert to the query builder is:
$test = Db::table('wouter_blog_posts')
->where('published', '=', 1)
->where('published', '=', 'IS NOT NULL')
->where('published_at', '=', 'IS NOT NULL')
->where('published_at', '<', 'NOW()')
->select(Db::raw('count(*) wouter_blog_tags'))
->join('wouter_blog_posts_tags', function($join)
{
$join->on('wouter_blog_tags.id', '=', 'wouter_blog_posts_tags.tags_id')
->on('wouter_blog_posts_tags.post_id', '=', 'wouter_blog_posts.id')
->whereIn('id', $tagid[0]->id);
})
->get();
I have read that I can't use whereIn in a join. The error i now get:
Call to undefined method Illuminate\Database\Query\JoinClause::whereIn()
I realy dont know how I can convert my SQL to query builder. I hope when I see a good working conversion of my query I can understand how I have to do it next time.
This work for me:
DB::table('wouter_blog_posts')
->whereNotNull('published')
->where('published', 1)
->whereNotNull('published_at')
->whereRaw('published_at < NOW()')
->whereRaw("(SELECT count(*)
FROM wouter_blog_tags
INNER JOIN wouter_blog_posts_tags ON wouter_blog_tags.id = wouter_blog_posts_tags.tags_id
WHERE wouter_blog_posts_tags.post_id = wouter_blog_posts.id
AND id
IN (
'".$tagid."'
)) >=1")
->orderBy('published_at', 'desc')
->skip(0)
->take(10)
->paginate($this->property('postsPerPage'));
The following Query Builder code will give you the exact SQL query you have within your DB::select:
DB::table('wouter_blog_posts')
->whereNotNull('published')
->where('published', 1)
->whereNotNull('published_at')
->whereRaw('`published_at` < NOW()')
->where(DB::raw('1'), '<=', function ($query) use ($tagid) {
$query->from('wouter_blog_tags')
->select('count(*)')
->join('wouter_blog_posts_tags', 'wouter_blog_tags.id', '=', 'wouter_blog_posts_tags.tags_id')
->whereRaw('`wouter_blog_posts_tags`.`post_id` = `wouter_blog_posts`.`id`')
->whereIn('id', [$tagid[0]->id]);
})
->orderBy('published_at', 'desc')
->skip(0)
->take(10)
->get();
The subquery condition had to be reversed because you can't have a subquery as the first parameter of the where method and still be able to bind the condition value. So it's 1 <= (subquery) which is equivalent to (subquery) >= 1. The query generated by the above code will look like this:
SELECT *
FROM `wouter_blog_posts`
WHERE `published` IS NOT NULL
AND `published` = 1
AND `published_at` IS NOT NULL
AND `published_at` < Now()
AND 1 <= (SELECT `count(*)`
FROM `wouter_blog_tags`
INNER JOIN `wouter_blog_posts_tags`
ON `wouter_blog_tags`.`id` =
`wouter_blog_posts_tags`.`tags_id`
WHERE `wouter_blog_posts_tags`.`post_id` =
`wouter_blog_posts`.`id`
AND `id` IN ( ? ))
ORDER BY `published_at` DESC
LIMIT 10 offset 0
My process when creating more complex queries is to first create them and try them out in a SQL environment to make sure they work as indended. Then I implement them step by step with the Query Builder, but instead of using get() at the end of the query, I use toSql() which will give me a string representation of the query that will be generated by the Query Builder, allowing me to compare that to my original query to make sure it's the same.

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