How do i search two collection on the same _id - database

I'm working on a project of mine and I have encountered a problem. Let's suppose that we have three classes (models) respectively Person, Shop, Transaction: the first and second one (Person and shop) are both interacting by creating and pushing in arrays an instance of Transaction. They all look as follows :
Person
{
firstName:String,
lastName:String,
transactions:[ref:Transaction],
...other properties...
}
Shop
{
name:String,
customers:[ref:Person]
transactions:[ref:Transaction],
...other properties...}
}
Transaction
{
from:ref,//id of person||shop
to:ref, //id of person||shop
amount:float
...other properties...
}
Now when some one opens and ask the app for the balance (money they have) he/she should see a list of transaction and the name of the either of the two other class... so normal populate or lookup won't do cause in the two different collection the id's might be the same so one of the way I wanted to address it was by creating an extra id that would be used when creating any of the Person and Shop instance thus any will have its own id (example: person.id-> 1,shop.id->2). But we would do first a query on id in the Person collection and then if this result is null we would then perform the second query on id in the Shop collection... I don't really like this solution so if anyone reading this have a solution please share it with me ... Thanks in advance
Edit: The Person instances may also send transactions to one an other

Related

Is it possible for a pivot table to have a many-to-many relationship with yet another table?

Let's say there is a tasks table, and a user table. A task can have many users assigned through the user_task pivot table, which has a field is_done which tells if an assigned user has done the task. So far so good.
Now let's say there is also a subtasks table, and each task can have multiple subtasks.
Now if we also want to save for each assigned user which subtasks they are assigned to, for example in a user_task_subtask table.
So all tables would like like this:
user: [id, name]
task: [id, title]
subtask: [id, title, task_id]
user_task: [id, user_id, task_id, is_done]
user_task_subtask: [user_task_id, subtask_id]
Using eloquent, I assume I could type something like $task->users()->where('user_id', 1)->pivot->subtasks to access all the subtasks of user 1 for this particular task. I tried this:
class Task extends Model
{
public function users()
{
return $this
->belongsToMany(User::class)
->as('userdetails')
->withPivot('is_done')
->using(UserTaskDetails::class);
}
}
and then add an extra relationship on the pivot:
class UserTaskDetails extends Pivot
{
public function subtasks()
{
$this->belongsToMany(Subtask::class, 'user_task_subtask', ...); // <-- what to write here exactly?
}
}
But I cannot get this subtasks relationship to work properly. Can anyone help me out?
This is a bad idea i would go with parent_id concept for the subtasks instead of an seperate table. so tasks tables would contain another field called parent_id.

how to update document of many to many model

Need help,
Let's say I have a model of 2 tables with relation of many to many . teachers and students.
I thought to save a document per student. to be able to search by student name but to be able to filter also by the teacher.
so I thought to create the document like that:
{
id: string
studentName: string,
class: string
teachers: [teacherId1: string, teacherId2: string...]
...
}
but what should happens when I remove the teacher from some class, now I need to update all the class student's documents (and I have thousands, how much time it will take (my document itself is not huge)).
Is there an easy way to that? instead of updating a document one by one.
(let's say I have all the list of studentIds)
maybe my document model structure is not correct.
Is there any other good idea.
Thanks,

Best way to structure my shopping database?

Right now my database has the following (simplified) format:
ShoppingList
{
List<ListProduct> listProducts
}
ListProduct
{
int quantity
Product product
}
Product
{
information about the overall product...
List<StoreProduct> StoreProduct
}
StoreProduct
{
information about the specific product and the store
}
In general, a shoppinglist contains a list of listproducts which each contains their quantity and their product which each contains a list of storeproducts.
This all works great - however, in my shoppinglist I wanna keep track of which storeproducts were purchased. Now I can't just add a "purchased" boolean to my storeproducts since they are used across multiple shopping lists (static information).
I thought of adding a purchasedProduct property of ListProduct which would be set to the purchased storeProduct and otherwise be null.
However I'm unsure as to whether there exists any better solutions? My schema is complex already so I'd don't want to make it even more complex if it isn't necessary.
UPDATE:
Here's my customer table:
Customer
{
List<ShoppingList> shoppingLists
}
Why don't you make a new table with something like CustomerID column references to Customer and another column references StoreProduct. Use that to store all the purchased product. I would suggest you to list the Schema related to Customer for this kind of question.

Retrieving data from referenced key table - Laravel-4

The structure of concerning tables is as follows (MySQL):
//Table Name : team
tid PK
team_name (varchar)
//Table Name : fixture
fid PK
home_team_id FK |_ both referenced to 'tid' from 'team' table
away_team_id FK |
My aim is to retrieve the team names. Considering this structure, I think I'll have to retrieve home_team_id and away_team_id and then do something like
Fixture::where('tid','=',$home_team_id)->get();
My question is, is this the correct way to accomplish what I aim to do?
and
should this be done from the controller? (if so, then I'll have to do two queries from same function)
First, rather than having your primary keys be tid and fid, just keep them both as id. This is not only best practice, but will allow you to more easily use Laravel's Eloquent ORM as it by default assumes your primary key column is named id.
Second thing, make sure your table names are in plural form. Although this is not necessary, the example I'm about to give is using Laravel defaults, and Laravel assumes they are in plural form.
Anyway, once you've 'Laravelized' your database, you can use an Eloquent model to setup awesome relationships with very minimal work. Here's what I think you'd want to do.
app/models/Team.php
class Team extends Eloquent {
// Yes, this can be empty. It just needs to be declared.
}
app/models/Fixture.php
class Fixture extends Eloquent {
public function homeTeam()
{
return $this->belongsTo('Team', 'home_team_id');
}
public function awayTeam()
{
return $this->belongsTo('Team', 'away_team_id');
}
}
Above, we created a simple model Team which Laravel will automatically look for in the teams database table.
Second, we created model Fixture which again, Laravel will use the fixtures table for. In this model, we specified two relationships. The belongsTo relationship takes two parameters, what model it is related to, in both cases here they are teams, and what the column name is.
Laravel will automatically take the value in away_team_id and search it against the id column in your teams table.
With just this minimal amount of code, you can then do things like this.
$fixture = Fixture::find(1); // Retrieves the fixture with and id of 1.
$awayTeam = $fixture->awayTeam()->first(); // var_dump this to see what you get.
$homeTeam = $fixutre->homeTeam()->first();
Then you can proceed as normal and access the column names for the tables. So say you have a 'name' column in the teams table. You can echo out the the home team name from the fixture like so.
$fixture = Fixture::find(1); // Get the fixture.
echo $fixture->homeTeam->name;
It's nearly 2AM, so there might be an error or two above, but it should work.
Make sure you check the docs for Eloquent, especially the bits relating to relationships. Remember to name your columns and tables in the way Laravel wants you to. If you don't, there are ways to specify your custom names.
If you want to get even more fancy, you can define the inverse relationship like this on your Team model.
app/models/Team.php
class Team extends Eloquent {
public function fixturesAtHome()
{
return $this->hasMany('Fixture', 'home_team_id');
}
public function fixturesAway()
{
return $this->hasMany('Fixture', 'away_team_id');
}
}
Then to get all of a particular team's home fixtures...
$team = Team::find(1); // Retreive team with id of 1;
$homeFixtures = $team->fixturesAtHome();

objectify query filter by list in entity contains search parameter

in an app i have an entity that contains a list of other entities (let's say an event holding a list of assigned employees)
using objectify - i need to find all the events a particular employee is assigned to.
is there a basic way to filter a query if it contains the parameter - kind of the opposite of the query in
... quick pseudocode
findAll(Employee employee) {
...
return ofy.query(Event.class).filter("employees.contains", employee).list();
}
any help would be greatly appreciated
i tried just doing filter("employees", employee) after seeing this http://groups.google.com/group/objectify-appengine/browse_thread/thread/77ba676192c08e20 - but unfortunately this returns me an empty list
currently i'm doing something really inefficient - going through each event, iterating through the employees and adding them to a new list if it contains the given employee just to have something that works - i know this is not right though
let me add one thing,
the above query is not actually what it is, i was just using that because i did not think this would make a difference.
The Employee and Events are in the same entity group with Business as a parent
the actual query i am using is the following
ofy.query(Event.class).ancestor(businessKey).filter("employees", employee).list();
unfortunately this is still returning an empty list - does having the ancestor(key) in there mess up the filter?
solution, the employees field was not indexed correctly.
I added the datastore-indexes file to create a composite index, but was testing originally on a value that I added before the employees field was indexed, this was something stupid i was doing - simply having an index on the "business" field and the "employees" field fixed everything. the datastore-indexes file did not appear to be necessary, after deleting it and trying again everything worked fine.
Generally, you do this one of two ways:
Put a property of Set<Key<Employee>> on the Event
or
Put a property of Set<Key<Event>> on the Employee
You could also create a relationship entity, but if you're just doing filtering on values with relatively low counts, usually it's easier to just put the set property on one entity or the other.
Then filter as you describe:
ofy.query(Event.class).filter("employees", employee).list()
or
ofy.query(Employee.class).filter("events", event).list()
The list property should hold a Keys to the target entity. If you pass in an entity to the filter() method, Objectify will understand that you want to filter by the key instead.
Example :
/***************************************************/
#Entity
#Cache
public class News {
#Id Long id;
String news ;
#Index List<Long> friend_list = new ArrayList<Long>();
// My friends who can see my news , exemele : friend_list.add(id_f1); friend_list.add(id_f2); friend_list.add(id_f3);
//To make an operation on "friend_list", it is obligatory to index it
}
/*************************************************/
public News(Long id_f){
List<Long> friend_id = new ArrayList<Long>();
friend_id.add(id_f);
Query<Nesw> query = ofy().load().type(News.class).filter("friend_list in",friend_id).limit(limit);
//To filter a list, just after the name of the field you want to filter, add "IN".
//here ==> .filter("friend_list in",friend_id);
// if friend_list contains "id_friend" ==> the query return value
.........
}

Resources