Laravel Eloquent - How to group conditions - php

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

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

Laravel 5.2 whereRaw with muliple where conditions

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

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

How to display query assembled by ORM?

How to display query assembled by ORM ?
Example: SELECT article.id AS article:id, article.name AS article:name
I'm using the code below:
$query=DB::select('categories.*',
array(DB::expr('COUNT(categories.id)'), 'total'),
array(DB::expr('MIN(displays.price)'), 'min_price'),
array(DB::expr('MAX(displays.price)'), 'max_price'),
array(DB::expr('SUM(displays.is_offer)'), 'is_offer')
)
->from('categories')
->join('category_products', 'INNER')
->on('categories.id', '=', 'category_products.category_id')
->join('displays', 'INNER')
->on('category_products.product_id', '=', 'displays.product_id')
->where('displays.active', '>=', 1)
->group_by('categories.id')
->order_by('parent')
->order_by('total', 'desc');
Let's see, you're using DB::select() which returns a Database_Query_Builder_Select instance. In the doc it says
Database query builder for SELECT statements. See Query Builder for usage and examples.
And if you do see, you'll see
echo Debug::vars((string) $query);
// Should display:
// SELECT `username`, `password` FROM `users` WHERE `username` = 'john'
which makes sense once you see the __toString() from Database_Query_Builder_Select.
So
echo (string) $query;
should give you the query.

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