Uitableview, json and detail tableview - mysql

I am asking a very simple question for someone who has encountered this kind of problem, please don't mark it down because there are many approaches to a solution.
I have a database which has cities and town, cities has many town, therefore, using one query displays many cities to correspond to the town. The result is as follows from mysql;
{City - town 1, town2, town 3} therefore if I want to display both the town and cities, I will end up with {city-town1, city-town2, city-town3}
I want to be able to compile all towns under a city, so that I can eventually use this source of array for my drilldown table, i.e on the first table; I want a list of non-repeating cities, on detail table, a list of all towns under that city. I only want to use one table and make the array dynamic such that I can add cities and towns without any problems (I have seen examples proposing different tables for different arrays)
I used this for- loop to iterate through mysql result
for (int i=0; i<json.count; i++)
{
ids= [[json objectAtIndex:i] objectForKey:#"Id"];
cityName = [[json objectAtIndex:i] objectForKey:#"cityName"];
townName = [[json objectAtIndex:i] objectForKey:#"townName"];
}
This gives me a list of cities but they are repeating;
I have been thinking about different approaches;
1)use #distinctunion- (Key-Value Coding)
2)use two jsons (one for city and another for towns) -compile arrays under each then join them using common id
3)use an iteration, iterate as shown above, but also search for similar cityNames and group towns under cities
Has anyone encountered a similar situation? what did you do? could you give an example if possible please
This is JSON Result for NSMutable Array of the above iteration
2013-09-18 07:50:52.025 JSONDATA[7119:11603] (
Bath,
"Bath, Somerset"
)
2013-09-18 07:50:52.035 JSONDATA[7119:11603] (
Bath,
"Bath, Somerset"
)
2013-09-18 07:50:52.035 JSONDATA[7119:11603] (
Bath,
Keynsham
)
2013-09-18 07:50:52.035 JSONDATA[7119:11603] (
Bath,
Keynsham
)

Related

How can i adjust joined table query result in needed JSON format with CodeIngiter

Suppose we have table person and table phoneand the relation between them is one to many.
I need to retrieve this like result with one query.
[
{
name:"abc",
lname:"def",
phones:[
{
dial_code="+1",
number:"12345667"
},
{
dial_code="+1",
number:"12345667"
}
]
},
{
name:"xyz",
lname:"lmn",
phones[
{
dial_code="+2",
number:"2643525"
}
]
},
{...}
]
I can do this by multiple query like first getting all persons and then get their phones one by one but i think its so weird and need lots of time and reduce performance. and if i get all data by joining table it wouldn't be like this JSON format.
Any idea will be appreciated.
Sorry for my bad English.
First things first, you cannot retrieve the desired result with multiple phone inside each person with one single query.
Now, running the query inside person loop will hugely affect the performance of the script if there are a lot of data. In this way, first, you need to execute a query to fetch all persons(say n persons). Then you have to again loop all n persons to fetch their respective phones.
So you need to run something like following inside $persons loop n times:
SELECT * FROM phone WHERE person_id = [$person_id]
Therefore in this way you need to execute n+1 queries.
To overcome this n+1 query problem we can apply a methodology which is called as eager loading. Here you also need to execute the first query to retrieve all persons and then write a query to fetch all phones which belongs to those retrieved persons:
SELECT * FROM person
Result($persons):
id name
5 John
10 Bob
20 Jenna
SELECT * FROM phone WHERE person_id IN (5,10,20)
Result($phones):
id person_id dial_code number
1 5 +2 12345
2 10 +1 12312
3 20 +1 98765
Now we combine these two results in PHP scripts to produce the desired array. In this way, we write only two queries instead of n+1 queries.
You can write a PHP script like following to combine the two result sets:
// Create an array of phones with person_id as key
$phones_with_person_id_as_key = [];
foreach($phones as $key => $phone) {
$phones_with_person_id_as_key[$phone->person_id][$key] = $phone;
}
// Loop $persons array and add phones to person object
foreach($persons as $key => $person) {
// create phones key and add data
if (!empty($phones_with_person_id_as_key[$person->id])) {
$person->phones = $phones_with_person_id_as_key[$person->id];
}
else {
$person->phones = [];
}
}
Now $persons contains the formatted desired output.

Groupby array by multiple values

I have an array I want to use groupby angular's filter and to group it by an array of criterias. Is there any way to do this? I guess I might use revision but I don't know how.
For example I have array of football teams. Each team have color, number of players, name, city, country.
I have array of data filters -country, city, players and color and I want to use groupby in the order of this array
not sure about angular. but just include underscore (it's more known for array/object manipulation) into your project then:
say you had an array of objects like an array of these:
car = {
make: "nissan",
model: "sunny",
color: "red"
};
then you'd just go:
var redCars = _.groupBy(cars, 'color');

Complicated Laravel relationship to generate view

I have Orders which contain any number of items stored in the items table (so a belongsToMany relationship between the two). The items are also categorized under itemtypes. When creating or editing an order I would like to load all items, categorized by itemtype, whether or not that order has any of the items. I was able to pull that up generically using the following:
$itemtypes = \App\Itemtype::with('items')
->orderBy('id','asc')
->get();
Then I loop through:
#foreach( $itemtypes as $itemtype )
{{$itemtype->name}}
#foreach( $itemtype->items as $item )
{{$item->name}}
#endforeach
#endforeach
This gives me something like:
NICU Items
- Baby Blanket
- Beaded Baby Cuddler
Miscellaneous Items
- Fitted Sheet
- Microfiber Towel
However, when I'm accessing a specific order which has records in item_order I want to display the saved quantities (stored in the pivot table). I know one way would be to add records for all items to item_order for every order created but that seems rather inefficient.
Item.php
public function orders() {
return $this->belongsToMany('App\Order', 'item_order', 'item_id', 'order_id') -> withPivot('id','quantity','createdby_user_id','weight','cost_billed', 'calc_by_weight', 'track_units');
}
Order.php
public function items() {
return $this -> belongsToMany('App\Item', 'item_order', 'order_id', 'item_id') -> withPivot('id','quantity','quantity_received','quantity_delivered','notes', 'createdby_user_id', 'weight', 'cost_billed', 'calc_by_weight', 'track_units');
}
UPDATE
I'm on the trail to a solution. I'm converting the collection to an array, loaded up with all items, modifying the array as needed, then using array_merge to replace the items that have quantities already in item_order.
This all works great - the only issue I'm having now is that when I load the order with it's items, items have an itemtype - a categorization and I'd like to group them by that. I'm not sure how to add a groupby to a relationship. If I figure it all out i'll post the full answer then.

Play 2.0 Complex join query how to parse (Anorm )

I am writing website using play 2.0 framework. And I have a problem when parsing results.
This request to mysql db gets all the links(can be several per episode) added to the database per episode together with all the information about episode and anime.
def lastReleasedLink(limit:Long=5):List[(((Episode,Anime),Link),Genre)] = {
DB.withConnection { implicit c =>
SQL(
"""
select * from yas_episodes as a
inner join anime as b on a.ep_anime_id=b.id
left outer join yas_links as c on a.ep_id=c.ep_id
LEFT JOIN yas_animes_genres AS d ON a.ep_anime_id = d.ag_anime_id
INNER JOIN yas_genres AS e ON e.g_id = d.ag_genre_id
where c.ep_id IS NOT NULL group by c.ep_id order by c.date desc limit {limit}
""").on('limit ->limit)as(Episode.simple~Anime.simple~Link.simple~Genre.simple map{
case episode~anime~link~genre => episode -> anime -> link -> Genre
} *)
}
}
The return value is type of List[(((Episode,Anime),Link),Genre)]
but how can I form output to the list of
let say List[episode,anime,Seq[links]] or List[episode,anime,Seq[Genres],Seq[links]] don't know where to put genres.
You can imagine that when you have two links per one episode information from table anime and yas_episodes will be copied for every row. So I need somehow stack them together(group) by episode record. Then it will be possible to iterate list and access to all objects.
As you can see, in the request there is many-to-many relation of anime with genres.
I have no idea how can I put all together to one list to be able to access it in view. Should Genre be part of Anime model?
It seems that the preferred way to achieve this is using the Scala collection API, see this post by Guillaume Bort.
In your case, I think you could do something like
lastReleasedLink groupBy { case (((e, a), l), g) => (e, a) }
to group by (Episode, Anime). Generally speaking, those manipulations are probably a little easier if you change your function to return a List[(Episode, Anime, Link, Genre)], i.e.
case episode~anime~link~genre => (episode, anime, link, genre)
then you could achieve the same with this code:
lastReleasedLink groupBy ((_._1, _._2))

Development of railway enquiry system, how to model Trains, Stations and Stops?

For example, if I have two trains, X and Y and they travel:
TRAIN.........STATIONS
Train-X : Goes Via Station-A; Station-B; Station-C; Station-D
Train-Y : Goes Via Station-B; Station-X; Station-D; Station-Y
How would I go about putting this information in a database so that if a passenger inquired about What trains start as Station-B? and What trains End as Station-D? then both Train-X and Train-Y should come in the result.
I would say you need to have three tables to make this work.
Station: station ID, name, etc.
Service: service ID, operator, number of train cars perhaps, etc.
Service_Stop: service ID, stop number, station ID.
You can then find services that stop at Station-B and subsequently at Station-D using a query something like the following:
SELECT
Service_ID
FROM
Station AS Start_Station
JOIN Service_Stop AS Start_Stop ON
Start_Station.Station_ID = Start_Stop.Station_ID
JOIN Service_Stop AS End_Stop ON
Start_Stop.Service_ID = End_Stop.Service_ID AND
Start_Stop.Stop_Number < End_Stop.Stop_Number
JOIN Station AS End_Station ON
End_Stop.Station_ID = End_Station.Station_ID AND
End_Station.Name = "Station-D"
WHERE
Start_Station.Name = 'Station-B'
I would use five tables:.
Train: train_id, name # e.g "The UnionT522"
Station: station_id, name # e.g. "Eggles Place"
Route: route_id, route_name # e.g. "Afternoon special at 4pm"
RouteStation: route_station_id, route_id, station_id, route_order, begin_flag, end_flag
TrainRoute: train_route_id, train_id, route_id # e.g. which train (above) is going on which route (above).
So RouteStation would have whether things began or ended at a given station for a given route.
TrainRoute would have information about which route a train is taking.