Has many through self join in batmanjs - has-many-through

I am trying to implement a has many through relationship as elaborated here. However, my related model is the same as the referring model by means of a self-join. I tried this:
class Article extends Batman.Model
#hasMany 'citations'
#hasMany 'usages', name: 'Citation', foreignKey: 'referenced_article_id'
#accessor 'referenced_articles', ->
#get('citations').mappedTo('referenced_article')
class Citation extends Batman.Model
#belongsTo 'article'
#belongsTo 'referenced_article', name: 'Article'
Unfortunately, calling my_article.get('referenced_articles') gives an error. Any ideas?

Ah, shoot. I didn't add mappedTo to SetProxy in 0.16. It's fixed with this PR: https://github.com/batmanjs/batman/pull/1052
You could either get master from batmanjs.org/download.html or monkey-patch it with:
Batman.AssociationSet::mappedTo = Batman.Set::mappedTo
(That's what I was doing til I updated to master)
Sorry!!

Since your association is named usages (not citations), you could try:
#accessor 'referenced_articles', ->
#get('usages').mappedTo('referenced_article')

Related

Relationships Between Primary Keys with Amplify Schema File

Normally I wouldn't try and create a relationship between primary keys within my Amplify Schema, though I am trying to recreate a friends code so that I can regularly deploy it with Amplify, hence I don't really have an option in this case.
My question is that I would like to create a link between these two Primary keys and was wondering if there is a way to do that, I have already followed the documentation here as well.
Ideally I would like to have my schema.graphql file look like this:
type ShoppingList #model #key(fields: ["UPC"]) {
UPC: Products #connection
quantity: Int
timestamp: Int
}
type Products #model #key(fields: ["UPC"]) {
UPC: String!
Description: String
Name: String
Price: Float
ProductId: String
combinedSeaarchKey: String
Img_URL: String
LongDescription: String
UserForRecommendations: Boolean
Hidden: Boolean
TrainingImageWidthInches: Float
}
When trying to deploy this, I get the error "Expected scalar and got Products".
Ideally I want to have the schema the same as well, since I don't want to go re-writing my friends client side application, and would rather try and fix it in the schema!
Hence any help would be greatly appreciated! Thanks
Was looking for a solution to the same general issue, came across your post, but then solved my issue. My issue was a little unrelated, I was trying to sort on a non-scalar field. In your case, you're receiving that error by trying to make a key out of a non-scalar entity. Remove that #key from ShoppingList and you should clear your error, but let's talk through what I believe you're trying to achieve.
I assume you're trying to make a 1:Many relationship between ShoppingList and Products.
In your ShoppingList code, you have Products as a single entity but likely meant to have an array of Products:
UPC: [Products]
From there you need to define your connection between UPC and Products. You correctly called out the use of #connection, but didn't create the connection. To create the connection in a 1:Many relationship, you're going to want 1 ShoppingList and many Products. To achieve this, you likely want the following:
type ShoppingList #model {
id: ID! #make sure you're specifying a PK for each object
UPC: [Products] #connection(keyName: "relatedShoppingList" fields: ["id"])
quantity: Int
timestamp: Int
}
type Products #model {
id: ID!
parentShoppingList: ShoppingList #connection(fields: "relatedShoppingList")
UPC: String!
Description: String
Name: String
Price: Float
ProductId: String
combinedSearchKey: String
Img_URL: String
LongDescription: String
UserForRecommendations: Boolean
Hidden: Boolean
TrainingImageWidthInches: Float
}
I foresee some additional issues with your data setup, but this should unblock your 1:many relationship between products and shopping lists.

Prisma deploy embedded in two fields error like bug

I would like to have two colums with the same type of data
from and to
this is a very simple example about the error
datamodel.prisma file with a one columns from: Address!
// it runs fine
type Travel {
id: ID! #id
from: Address!
}
type Address #embedded {
district: String!
}
datamodel.prisma file with two field with the same embedded from: Address! to: Address!
// it runs fine
type Travel {
id: ID! #id
from: Address!
to: Address!
}
type Address #embedded {
district: String!
}
It throws the error
Errors:
Travel
✖ The relation field `from` must specify a `#relation` directive: `#relation(name: "MyRelation")`
✖ The relation field `to` must specify a `#relation` directive: `#relation(name: "MyRelation")`
According to Prisma's documentation on Data Modeling (see also Datamodel (MongoDB) as your use of the #embedded directive hints that you might be using a document database), the name argument of the #relation directive is needed when your data model contains ambiguous relations.
In your example, there are two different relations between Travel and Address!, so it seems that Prisma wants you to disambiguate those.
A very similar question appears here (and has a more detailed answer than mine): Can’t create two or more relations to User (from / to) on Event.

Attach author to POST request to create an object

It's probably very basic, but I am starting to learn Django REST Framework. So far I've succeeded with read-only operations. And now I got stuck on this problem.
I have a model:
class PersonComment(AbstractComment):
person = models.ForeignKey(Person, on_delete=models.PROTECT)
author = models.ForeignKey('auth.User')
body = models.TextField(default='', blank=False)
(Here author is the author of the comment and person is a person this comment relates to; it's a genealogical site.) And a related serialiser:
class PersonCommentSerialiser(serializers.HyperlinkedModelSerializer):
class Meta:
model = PersonComment
fields = ('url', 'body', 'person', 'author')
In my HTML page, I expect a user to submit a comment by providing "body", the rest should be auto-filled. What is the best practice for filling in the "author"? In my pre-DRF Django exercises, I was doing something like this in the view:
comment = PersonComment.objects.create(
author=request.user,
body=new_comment_body,
person=person
)
But if I understand everything I've read so far, this is not the way in DRF. Any help is much appreciated.
I would do this using the default attribute in serializer fields.
class PersonCommentSerialiser(serializers.HyperlinkedModelSerializer):
author = serializers.PrimaryKeyRelatedField(read_only=True, default=CurrentUserDefault())
class Meta:
model = PersonComment
fields = ('url', 'body', 'person', 'author')
CurrentUserDefault is a class predefined in Django REST framework for exactly this purpose. This way you don't have to overwrite create in your own serializer.
I was not sure what is the difference between person and author. But you should be able to do something similar I suppose.

Why does Eloquent change relationship names on toArray call?

I'm encountering an annoying problem with Laravel and I'm hoping someone knows a way to override it...
This is for a system that allows sales reps to see inventory in their territories. I'm building an editor to allow our sales manager to go in and update the store ACL so he can manage his reps.
I have two related models:
class Store extends Eloquent {
public function StoreACLEntries()
{
return $this->hasMany("StoreACLEntry", "store_id");
}
}
class StoreACLEntry extends Eloquent {
public function Store()
{
return $this->belongsTo("Store");
}
}
The idea here is that a Store can have many entries in the ACL table.
The problem is this: I built a page which interacts with the server via AJAX. The manager can search in a variety of different ways and see the stores and the current restrictions for each from the ACL. My controller performs the search and returns the data (via AJAX) like this:
$stores = Store::where("searchCondition", "=", "whatever")
->with("StoreACLEntries")
->get();
return Response::json(array('stores' => $stores->toArray()));
The response that the client receives looks like this:
{
id: "some ID value",
store_ac_lentries: [
created_at: "2014-10-14 08:13:20"
field: "salesrep"
id: "1"
store_id: "5152-USA"
updated_at: "2014-10-14 08:13:20"
value: "salesrep ID value"
]
}
The problem is with the way the StoreACLEntries name is mutilated: it becomes store_ac_lentries. I've done a little digging and discovered it's the toArray method that's inserting those funky underscores.
So I have two questions: "why?" and "how do I stop it from doing that?"
It has something in common with automatic changing camelCase into snake_case. You should try to change your function name from StoreACLEntries to storeaclentries (lowercase) to remove this effect.

Laravel - Hierarchy in Eloquent model

my database have this hierarchy:
- Manager:
- Coordinator:
- Supervisor:
- Operator
this code, output all "coordinator" belongs to "manager":
Manager::find(1)->coordinator()->get();
is possible get all "supervisor" belongs to "coordinator" directly? Example:
Manager::find(1)->coordinator()->supervisor()->get();
Sorry by english, i'm brazilian
That is perfectly possible, you just need to define all the relationship in your models. Then you could retrieve all all your "operators" for a specific "manager" by doing:
Manager::find(1)->coordinator->supervisor->operator;
In that code, I'm using dynamic properites that come with Eloquent ORM.
When I said 'you need to defin all the relationships in your models' doing the following:
class Manager extends Eloquent
{
public function coordinator()
{
return $this->hasMany('Coordinator');
}
}
Then you will do the same for coordinator that has many supervisors and for supervisor that has many operators.
See the documentation about Relationship, one-to-many, in Laravel 4.

Resources