mysql 2 tables updation/deletion based on condition - php

Hello friends I have 2 Mysql tables with 1:N relationship between category and category_Dates
Category:
ID Category Frequency
1 Cat A Half-yearly
2 Cat B Quarterly
category_Dates:
ID CatID Date
1 1 01-Jan-15
2 1 01-Jul-15
3 2 01-Jan-15
4 2 01-Apr-15
5 2 01-Jul-15
6 2 01-Oct-15
based on the category frequency I am entering number of records automatically in category_date. Eg
When category frequency = quarterly, I am entering 4 records in category_date with ID of that category. And dates will be entered later.
I am little confused if in case on wants to edit the frequency from halfyearly to yearly. How to change number of records. Please help with your valuable suggestions. I am using laravel 4 framework with mysql

best way would be with 3rd table joining Dates and Categories. See little carefully ,you can see its actually Many to Many relationship (N to N) as 1 category can have multiple dates. and one date may be part of multiple categories, like say 01-Jan-15 is part of Category 1 and 2 as well.
So use
category table
id Category Frequency
1 Cat A Half-yearly
2 Cat B Quarterly
date table
id Date
1 01-Jan-15
2 01-Apr-15
3 01-Jul-15
4 01-Oct-15
categories_dates table
ID CatID Date_id
1 1 1
2 1 3
3 2 1
4 2 2
5 2 3
6 2 4

If you change the frequency in Category table, retrieve the update category_id,
delete all from category_dates where CatId=category_id then insert the new entries in category_Dates.
Hope this help.
I assume your models are Category and CategoryDates.
let's update category id 1 from Half-yearlyto to Quarterly
$query = Category::find(1);
$query -> Frequency = 'Quarterly';
$query -> save();
return $query -> id;
in the CategoryDates model you would delete the catID = 1 and insert new data
$catID = 1;
$query = CategoryModel::where('CatId',$catId) -> delete();
$data = ['CatId' => $catID,'date' => 01-Jan-15, ....];
CategoryModel::create($data);
of course assuming that you would return the newly updated category id to your controller and call a funtionn to do the update in your CategoryModel.
Hope this help.

Related

Finding the most repeating id by laravel eloquent group

$device = SalesItem::where('type', '=', 1)->get()->groupBy('product_id');
There is a list of products in the database. Here I am storing the product id. The same product can be idsi. I want to get the id data of the product with the same id at most.
Sample:
ID type product_id
1 1 1
2 1 1
3 1 1
4 1 1
5 1 1
6 1 2
7 1 2
8 1 1
9 1 1
0 1 1
output: 1
here I want the output to give product id 1. I couldn't find what to do after group by. Can you guide me on this?
I don't think there is an elegant way to do this in, but this should work for you:
Note: I'm unsure of your table name.
$device = DB::table('sales_item')
->select('product_id', DB::raw('COUNT(product_id) AS magnitude'))
->where('type', 1)
->groupBy('product_id)
->orderBy('magnitude', 'DESC')
->limit(1);
It goes into the table and selected the id, type, and the COUNT() of product_id. Which it then groups by the product_id and orders by the count('product_id') from high to low.
->limit(1) is used to only select the first (read highest) value.

How to get the Hierarchy recursively in laravel

I have 2 tables i.e. users and user_managers, with the following structure and data:
users
id
name
employee_number
1
Employee One
ACB1234
2
Employee Two
XYZ1234
3
Employee Three
EFG1234
4
Employee Four
HIJ1234
user_managers
id
user_id
manager_of_user_id
1
1
2
2
2
3
3
4
1
4
5
4
I want a recursive function to get the complete chain of the managers. For example, if query for user_id = 4, I should get the following result:
result
user_id
name
employee_id
comments
1
Employee One
ABC1234
user managed by 4
2
Employee Two
XYZ1234
user managed by 1
3
Employee Three
EFG1234
managd by user 2
5
Employee Five
JKL1234
manager of user 4
The table above is just for the clarification, I am looking for a recursive function to get the above result.
I have tried the below solution but it is working for only 1 level.
public static function getCompleteChain(User $user)
{
$managerUsers = $user->managers;
foreach ($managerUsers as $manager) {
$manager->user = User::where('employee_id', $manager->manager_of_user_id)->first();
self::getCompleteChain($manager->user);
}
return $managerUsers;
}
Thanks in advance.

Get the latest record of a particular id in a table

ScholarCard
scholar_card_id grade scholar_id
1 grade-1 1
2 grade-1 2
3 grade-2 1
4 grade-2 2
5 grade-3 1
$scholar_cards = ScholarCard::where('scholar_id','=',$scholar_id)->orderBy('scholar_card_id','DESC')->get();
I have a table for a card of grades and i want to display the latest created card.
Like for example for scholar_id 1,there are three 1 on the column.How do you display only
the scholar_id 1 with the latest or last creation.This table has only few record for simplicity.
You could use first() function. Try this:
$scholar_card = ScholarCard::where('scholar_id','=',$scholar_id)
->orderBy('scholar_card_id','DESC')
->first();

Codeigniter correct JOIN request

I have 2 tables with next construction & data:
Table 1 - events:
id name about owner_id
1 Event1 <description> 2
2 Event2 <description> 1
3 Event3 <description> 2
4 Event4 <description> 2
And table 2 - event_follows
id event_id user_id
1 1 2
2 4 2
I need to get all events for current user (i.e. user with id 2) and join count of followers for this event. Now I'm using this code:
$this->db->select('events.*, COUNT(event_follows.id) as followers')
->from('events')
->where('events.owner_id', $id); // $id - equals 2
$this->db->join('event_follows', 'event_follows.event_id = events.id', 'left')
->group_by('event_follows.event_id');
All seems to be ok, but there is a problem. This code returns only 2 events of 3 - events with id 1 & 4. As I understand, this happens because there is no followers for event 3.
So how to correctly fetch all events and get count of it's followers, including those that have 0 followers?
In order to get all rows from the events table you need to group by events.id as opposed to event_follows.event_id
$this->db->select('events.*, COUNT(event_follows.id) as followers')
->from('events')
->where('events.user_id', $id); // $id - equals 2
$this->db->join('event_follows', 'event_follows.event_id = events.id', 'left')
->group_by('events.id'); //change to events.id

Avoiding duplicates Database records in a datamapper code igniter

My Question is simply how to insert data into the join table(user_book) without inserting a duplicate entry into the main table(book).
Mainly consider we have tree table below
id Users id Books id Users Books
1 Sam 1 B1 1 1 1
2 Ben 2 B2 2 1 3
3 Mike 3 B3 3 3 3
4 2 2
But the problem is when I am inserting a new book(ex Mike like B3) that exist in the Books table. The duplicate will appear in the books table and the above table will be like:
id Users id Books id Users Books
1 Sam 1 B1 1 1 1
2 Ben 2 B2 2 1 3
3 Mike 3 B3 3 3 4
4 B3 4 2 2
Is that make sense now what I am trying to resolve? Or maybe I can't have a unique list of books at all?
if I am going to insert
Given the database
users and books
users<--->books are related by users_books
we need to make sure that when we insert a book record to the db it is not a duplicate. Further, if the book exist, a relation will be inserted and not the book record . How can one do that?
One approach is to say
$m=new Book();
$m->where('id_book', $data['user_booklist'][$i]['id'])->get();
$u = new User();
$u -> where('id_user', $data['user_profile']['id'])-> get();
if(!$u->where_related($m))
{
$m -> name = $data['user_booklist'][$i]['name'];
$m -> id_book = $data['user_booklist'][$i]['id'];
$m -> save($u);
}
if (book->exist) in the "books" table
then check the relation and see if there is a relationship between users and books and if there is then don't insert it. Further do I need to change any thing in the mysql db structure to avoid this.
The above code is not working but should give an idea what I am talking about.
Update:
In summary, if two users liked the same book, I just want to insert a record(book) into the join table (users_books) and while not to creating a new record in the table. Using the unique sql tag did not work since it keeps unique list but it prevents from inserting the multiple relationships into the join table users_books.
You could do:
$b = new book();
$b->where('id_book', $data['user_booklist'][$i]['id'])->get();
// I believe you can do this as well, but I'm not sure:
// $b->where('id', $data['user_booklist'][$i]['id'])->get();
$u = new user();
$u -> where('id_user', $data['user_profile']['id'])-> get();
if( $b->exists() && $u->exists() )
{
// This saves the relationship between the book and the user
$b->save($u);
}
else
{
// Could not find the book or the user
}
You should check out the datamapper-manual on saving relationships.

Categories