How to increment database field values by 1 in Laravel - laravel-4

I have a table student attendance.
Fields/data sample
id | studid | cls_id | smonth | syear | total_p | total_a
1 | 20 | 2 | 08 | 2015 | 2 | 1
2 | 21 | 2 | 08 | 2015 | 1 | 0
3 | 22 | 2 | 08 | 2015 | 2 | 1
I want, to check what is the total_p and total_a value of each students in last update and then increment 1.
If I am enter the both students are present = 1 so I want total_p value 20=3, 21=2, 22=3
How to get database field values and increment 1's.?
My controller
$present = Input::get($student->id);
if ($checkatt)
{
if ($present == 1)
{
DB::table($wys_total_attend_table)->where('studid', $student->id)
->where('smonth', $date_exploded[1])
->where('syear', $date_exploded[2])
->where('stotal_p', 1)
->update(array(
'stotal_p' => 1 + 1,
));
DB::table($wys_total_attend_table)->where('studid', $student->id)
->where('smonth', $date_exploded[1])
->where('syear', $date_exploded[2])
->where('stotal_p', 0)
->update(array(
'stotal_p' => 1,
'stotal_a' => 0,
));
} elseif ($present == 0)
{
DB::table($wys_total_attend_table)->where('studid', $student->id)
->where('smonth', $date_exploded[1])
->where('syear', $date_exploded[2])
->where('stotal_a', 1)
->update(array(
'stotal_a' => 1 + 1,
));
DB::table($wys_total_attend_table)->where('studid', $student->id)
->where('smonth', $date_exploded[1])
->where('syear', $date_exploded[2])
->where('stotal_a', 0)
->update(array(
'stotal_a' => 1,
));
DB::table($wys_total_attend_table)->where('studid', $student->id)
->where('smonth', $date_exploded[1])
->where('syear', $date_exploded[2])
->where('stotal_p', 1)
->where('stotal_a', 0)
->update(array(
'stotal_a' => 0 + 1,
));
}
}

I think u just want to update each record of total_p and total_a column just make it simple:
//get the id of student
$student_id = Input::get('student_id');
$present = Input::get('status'); //dropdown value 0,1
//You need a model for your table let say:
#Student.php
<?php
class Student extends Eloquent{
protected $table = 'students'; //table name
}
//Your Controller codes
public function findStudent($id, $status){
$query=Student::find($id);
if($query->count() && $status==1 ){ //status 1 = present
$query->total_p += 1; //plus one value in the total_p column in the tbl.
$query->save();
}else{
$query->total_a +=1;
$query->save();
}
}

Related

How to get all unique records with the maximum value in column using LINQ

Learner | AssesmentId | Attempt
------------------------------------
Parker | 1 | 1
Parker | 1 | 2
Stark | 1 | 1
Rogers | 1 | 1
Rogers | 1 | 2
Parker | 1 | 3
Given this data, how do I get all the unique Student name with the highest Attempt?
I'm attempting to get this result:
Learner | AssesmentId | Attempt
------------------------------------
Parker | 1 | 3
Stark | 1 | 1
Rogers | 1 | 2
How can I do this in a single query in LINQ?
from la in _context.LearnerAssessments
where la.AssessmentId == assessmentId
&& learnerIds.Contains(la.LearnerId)
&& la.Attempt == {highest attempt}
var data = from list in _context.LearnerAssessments
group list by new
{
list.Learner,
list.AssesmentId
}
into g
select new
{
g.Key.Learner,
g.Key.AssesmentId,
Max= g.Max(x=>x.Attempt)
};
or using fluent API :
var data = _context.LearnerAssessments.GroupBy(l => new { l.Learner, l.AssesmentId }, (keys, item) => new
{
Key = keys,
MaxAttemp = item.Max(x => x.Attempt)
}).Select(x => new LearnerAssessment
{
Learner = x.Key.Learner,
Attempt = x.MaxAttemp,
AssesmentId = x.Key.AssesmentId
});

Laravel 9 - Sorting Polymorphic Relationship

I have the given table structure:
// table: examples
+ -- + ---- +
| id | name |
+ -- + ---- +
| 1 | Test |
| 2 | Test |
+ -- + ---- +
// table: example_data
+ -- + --------------- + ------------------ + --- + ----------------- +
| id | example_data_id | exmaple_data_type | key | value |
+ -- + --------------- + ------------------ + ------------|---------- +
| 1 | 1 | App\Models\Example | external | 1 |
| 2 | 1 | App\Models\Example | otherKey | string |
| 3 | 2 | App\Models\Example | external | 0 |
+ -- + --------------- + ------------------ + ----------- + --------- +
// Example Model:
public function daten()
{
return $this->morphMany(ExampleData::class, 'example_data');
}
// ExampleData Model:
public function example_data()
{
return $this->morphTo();
}
How I can order my examples by "value" in "example_data" with key = "external"?
$examples = Example::with('daten')
->orderBy(***value from external in daten***) // something like this 'Example->daten->key="external" ==> orderBy Example->daten->value'
->paginate($request->total);
Is it possible with orderBy and callback? How is the callback?
Does this answer your question:
$examples = Example::with(['daten' => function($query) {
$query->orderBy('key', 'asc');
}])
->paginate($request->total);
This will order the key column by ascending.
If you want only records where key is equal to external you can do this:
$examples = Example::with(['daten' => function($query) {
$query->where('key', 'external');
$query->orderBy('value', 'desc');
}])
->paginate($request->total);
And sort it by the value column.

Performance of whereHas laravel

I have read many articles warning about whereHas(it use subquery in where exists) performance when the data is big(Here: 18415, 5328, ...). In my case below will I need to replace it? And how?.
Table products
+----+---------------------+
| id | created_at |
+----+---------------------+
| 1 | 2020-10-10 10:10:10 |
| 2 | 2020-10-10 10:10:10 |
+----+---------------------+
Table product_translations(indexes: map_id, language_code, slug)
+----+--------+---------------+-----------+-----------+
| id | map_id | language_code | name | slug |
+----+--------+---------------+-----------+-----------+
| 1 | 1 | en | name en 1 | name-en-1 |
| 2 | 1 | es | name es 1 | name-es-1 |
| 3 | 2 | en | name en 2 | name-en-2 |
| 4 | 2 | es | name es 2 | name-es-2 |
+----+--------+---------------+-----------+-----------+
Product.php
function translation(){
return $this->hasOne('App\Models\ProductTranslation', 'map_id', 'id');
}
ProductController.php
function view($slug){
$currentItem = Product::with(['translation' => function($q) use($slug){
$q->where(['slug' => $slug, 'language_code' => \App::getLocale()]);
}])->whereHas('translation', function($q) use ($slug){
$q->where(['slug' => $slug, 'language_code' => \App::getLocale()]);
})
if ($currentItem == null) {
abort(404);
}
return view('product.view', compact('currentItem'));
}
I'm using laravel 8x.
You can replace whereHas with whereIn.
$currentItem = Product::with(['translation' => function($q) use($slug){
$q->where(['slug' => $slug, 'language_code' => \App::getLocale()]);
}])->whereIn(
'id',
ProductTranslation::select('map_id')
->where(['slug' => $slug, 'language_code' => \App::getLocale()])
);
Select the foreign key from a subselect and uses it with where in.

How can i get all date even dates that don't have a record by eloquent with group by?

I have a method that get a month parameter to select rows of that month from users table. I want to show count of registered user for a month.
public function registeredUsersDaily($month)
{
$countOfDailyRegisteredUsersForAMonth = User::user()
->where(DB::raw('created_at'), '=', $month)
->groupBy('date')
->orderBy('date')
->get([
DB::raw('DATE(created_at) as date'),
DB::raw('COUNT(*) as count')
]);
dd($countOfDailyRegisteredUsersForAMonth);
}
It return count only for dates that exists in users table, so i want to have zero for dates that don't exists.
|date|count|
| 5 | 10 |
| 15 | 3 |
I want to have a result like this:
|date |count |
| 1 | 0 |
| 2 | 0 |
| 3 | 0 |
| 4 | 0 |
| 5 | 10 |
| 6 | 0 |
| 7 | 0 |
| 8 | 0 |
| 9 | 0 |
| 10 | 0 |
| 11 | 0 |
| 12 | 0 |
| 13 | 0 |
| 14 | 0 |
| 15 | 3 |
....
Please check out like this
$dateValues = array_column($countOfDailyRegisteredUsersForAMonth, "date");
$maxDate = max($dateValues);
$likeYouWant=[];
for ($i = 1; $i <= $maxDate; $i++)
{
$likeYouWant[] = ["date" => $i, "count" => in_array($i, $dateValues) ? $countOfDailyRegisteredUsersForAMonth[array_search($i, $dateValues)]["count"] : 0];
}
print_r($likeYouWant);
If you want default date than you can mention in that migration file or you can also do that in your model from where you can retrieve data when there is no date given by user.
You can also refer this for more
How to pass default values to controller by routing in Laravel 5?
From what I've got from the comments:
I think the best thing here is to count the number of users created each day of the month. This will get you zero's in case no one registered on a given date.
With this, you'd probably loop through the dates checking the total users registered each date.
For instance, let's try to get the users created the last 30 days from now:
$results = [];
$startOfDay = now()->createMidnightDate();
for($i=0; $i<=30; $i++)
{
$total_count = User::whereBetween('created_at', [$startOfDay->subDays($i-1), $startOfDay->subDays($i)])
->count();
array_push($results[ $startOfDay->subDays($i)->format('d')], $total_count);
}
With this I think you can now work with the results from the array.

Yii2 AR left join with where and relations

Book
----------------------------
| id | name | published |
----------------------------
| 1 | book1 | 1 |
| 2 | book2 | 1 |
| 3 | book3 | 0 |
Chapter
----------------------------
| id | book_id | name | published |
----------------------------
| 1 | 1 | chapter1 | 1 |
| 2 | 1 | chapter2 | 0 |
| 2 | 2 | chapter1 | 0 |
| 3 | 3 | chapter1 | 1 |
class Book{
public function getChapter()
{
return $this->hasMany(Chapter::className(), ['kook_id' => 'id']);
} }
class Chapter{
public function getBook()
{
return $this->hasOne(Book::className(), ['id' => 'book_id']);
} }
How can i get published books with published pages using ActiveRecord (i want get book1 with chapter1 and book2 without any chapters)?
smth like Book::find($id)->where(['published' => 1])-> {{{left join with where}}} ->all())
ADDED
And then i wand to use it
echo $book->name;
foreach($book->getChapter() as chapter){
echo chapter->name;
}
Change your Book class relation as
class Book
{
public function getChapter()
{
return $this->hasMany(Chapter::className(), ['book_id' => 'id'])->where(['published' => 1]);
}
}
To get Related Records use with()
Book::find()->with(['chapter'])->where(['id' => $id ,'published' => 1])->all()
To Use it:
//Book Name
echo $book->name;
//For Chapters Name
if($book->chapter){
foreach($book->chapter as $chapter){
echo $chapter->name;
}
}

Resources