Is there any way to get the next birthdays using only DQL (Doctrine Query Language)?
I have solved the problem using the SQL function DAYOFYEAR, but I would like to have a DQL solution, in case I need to migrate to MSSQL (for example) where this doesn't work.
You don't really need the function from MySQL. Simply use PHP's date function and use format "z". Quoting the PHP docs:
z -> The day of the year (starting from 0) -> 0 through 365
Alternatively, you can also use strftime with "%j" (or anything else that suits you)
I found a way to get upcoming birthdays by using native query in doctrine.
This is a quick query and according to http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/native-sql.html Doctrine uses ResultSetMapping the same way internally when you create DQL queries.
This finds all the birthdays the next 30 days.
Use this method with care since it will affect how the entity is loaded later. Later in the script, only those fields added to the mapping will be loaded for this entity. I loaded the list by ajax ( and addded it to session )
use Doctrine\ORM\Query\ResultSetMapping;
$rsm = new ResultSetMapping;
$rsm->addEntityResult('AppBundle:User', 'u');
$rsm->addFieldResult('u', 'id', 'id');
$rsm->addFieldResult('u', 'firstname', 'firstname');
$rsm->addFieldResult('u', 'lastname', 'lastname');
$rsm->addFieldResult('u', 'birthday', 'birthday');
$rsm->addFieldResult('u', 'image', 'image');
$query = $this->entityManager->createNativeQuery("
SELECT *
FROM user u
WHERE DAYOFYEAR(u.birthday)
BETWEEN DAYOFYEAR(CURDATE()) AND DAYOFYEAR(DATE_ADD(CURDATE(), INTERVAL ? DAY))
ORDER BY DAYOFYEAR(u.birthday) ASC
", $rsm);
$query->setParameter(1, '30');
$birthdays = $query->getResult();
Related
I've been trying to convert a raw sql query to a Laravel Eloquent ORM query and I'm stuck.
SELECT *
FROM transaction_history
WHERE type = 'debit'
AND
(
description not in ('Premium Membership Balance Top Up', 'Sign Up Bonus')
OR
description in ('Premium Membership Balance Top Up', 'Sign Up Bonus') and extra_details is not null
)
I just started working on a Laravel project a couple weeks ago..my brain cells have exceeded their capacity by this time of day...and I have no idea where to even start. Help would be much appreciated.
Assuming you have a TransactionHistory eloquent model representing transaction_history table, you can try to use where clauses with logical parameter grouping to generate the desired query.
You can check the generated sql query by replacing get() with toSql() and then dumping the output dd($records);
$records = TransactionHistory::query()
->where('type', 'debit')
->where(function($query) {
$query->whereNotIn(
'description',
['Premium Membership Balance Top Up', 'Sign Up Bonus']
->orWhere(function($query) {
$query->whereIn(
'description',
['Premium Membership Balance Top Up', 'Sign Up Bonus']
)
->whereNotNull('extra_details');
});
})
->get();
Laravel 9.x Docs - Queries Logical Grouping
You need use Raw Expressions Query Builder in laravel eloquent ORM.
Visit laravel doc => Raw Expressions
You can use the raw query builder and just paste your query.
But the best way should be to create Models (think as table) and link those models with relationships (like foreign key).
Also, to get started, this tool can helps you to convert your query to a more laravel friendly query
Is there any way to put a manual function inside a query in Laravel.
I've timestamp saved in string in DB. I want to convert timestamp from one timezone to another. All the timestamp is inserted in one time zone, and depending upon my user I fetch the timestamp and convert it into their timezone.
what I want to achieve is something like this..
$query = BlogCategory::select('merchant_id', userTime(added_at))
->where('site_id', $site_id)
->get();
userTime() function takes two parameter, the timestamp and the timezone and converts the timsestamp to time of the user.
I want to use userTime() function before fetching the data. I dont want to fetch the data first and then do foreach and so on.
I know I might be absolutely absurd but is there anything of this sort in Laravel?
Well you can achieved that using collection map
$query = BlogCategory::select('merchant_id', 'added_at')
->where('site_id', $site_id)
->get();
$dateAdded = $query->map(function ($data) {
// try this if error $data['merchant_id']
return array(
'merchant_id' => $data->merchant_id,
'added_at' => $this->userTime($data->added_at)
);
})
dd($dateAdded);
Read Collection documentation here: https://laravel.com/docs/5.8/collections
You should use the selectRaw statement and let your DB do this logic for you if you don't want to loop over the result set.
For example if your underlying database is MySQL you can use the CONVERT_TIMEZONE function and do something like this.
BlogCategory::selectRaw('merchant_id, CONVERT_TZ(added_at, "GMT", "MET") as added_at')
->where('site_id', $site_id)
->get();
how select one month back records from current date from database in laravel. I am trying this code.
This is controller code.
class LoginHistoryController extends Controller {
public function index()
{
$login_history = LoginHistory::where('login_date','BETWEEN', '(CURDATE() -
INTERVAL 10 DAY) AND CURDATE()' )->get();
}
}
but i am getting error.
I will have a approach something like this. First I will calculate the date like
$today = date('Y-m-d');
$date = date_create($today);
date_sub($date, date_interval_create_from_date_string("30 days"));
$beforeOneMonth = date_format($date, "Y-m-d");
You should have the intended value in $beforeOneMonth by now. Now you can compare it in anyway you like whether you use IN operator or >=. For eg.
$login_history = LoginHistory::where('login_date','>=', $beforeOneMonth)->get();
Give it a try. If you are storing date in some other format, you can do your own tricks to format the date and do the thing
Another way to do it would be with whereRaw:
$login_history = LoginHistory::whereRaw(
'login_date BETWEEN (CURDATE() - INTERVAL 10 DAY) AND CURDATE()'
)->get();
Note that whereRaw has the side effect of making your code less portable since you're using SQL that might be specific to your database server. But sometimes you just can't do what you would like using the query builder.
I am trying to get the number of new users for each week using the created_at column. I am trying to use the whereBetweensyntax but it always return 0 even when it is suppose to return otherwise.
{{ DB::table('users')
->whereBetween('created_at', array(date("Y/m/d h:i:s", strtotime('sunday last week')), date("Y/m/d h:i:s", strtotime('saturday this week'))))->count(); }}
Any suggestions?
The query itself should work as written, though you might want to verify that created_at is a column of either timestamp, date, or datetime type. When you created the users table, did you use a migration to create your users table, and if so, did you specify $table->timestamps();? Or did you manually define the created_at column, and perhaps set it to a string?
A couple other (unrelated) suggestions:
• It appears that you're running this query in a view, echoing the count using blade. This logic would be better handled elsewhere, perhaps in your User model, and the result passed to the view by the controller.
• You can simplify your query using PHPs DateTime object, replacing your date(...strtotime...) with date_create(...):
$usersThisWeek = User::whereBetween(
'created_at', array(
date_create('sunday last week'),
date_create('saturday this week')
))->count();
I want to return all of the rows in my database table that are a day or less old. I'm using Laravel 4. This is what I tried:
$date = date('Y-m-d H:i:s');
return MainContact::where(DATEDIFF('timestamp', $date), '<=', 1)->get();
This doesn't work. I read the documentation and it doesn't seem like you can pass Laravel MySQL functions. timestamp is a datetime field. How can I compare these dates in Laravel 4?
The answer that user1977808 gave you is not good because MySQL can't use an index on the timestamp column, since it has to compute an output of the DATE_SUB function for every row. Avoid such queries, they have to process the entire table every time!
How about something like this:
return MainContact::where('timestamp', '>=', time() - (24*60*60))->get();
I put the >= in there because you said "a day or less old", so they must have timestamp that is later than yesterday.
Alternatively,
You can use Carbon API that bundle with Laravel.
ModelName::where( 'timestamp', '>=', Carbon::now() )->get();
Reference: http://laravel.com/docs/5.1/eloquent-mutators
You could also use whereDate(), whereDay(), whereMonth() and whereYear(). In this case, whereDate() could be used as such, with Carbon's easy date functions:
return MainContact::whereDate('dateField', '<', Carbon::now()->subDay())->get();
return MainContact::where('timestamp', '>=', time() - (24*60*60))->get();
You can also do a raw query by using:
$results = DB::query( 'query' );
You only don't the the model object back in the results var