Parent child relationships in Loopback - foreign-key-relationship

I have two loopback models, say Product and Service. They are related to a parent model Asset. The Asset has an AssetType which says if the current object is a Product or a Service. How do I model the entity relationships for this case?

Use polymorphic relations
https://loopback.io/doc/en/lb3/Polymorphic-relations.html
"parent": {
"type": "belongsTo",
"polymorphic": {
"foreignKey": "parentId",
"discriminator": "parentType"
}
}

Related

Laravel create/save a model with multiple relations

I have 3 tables. 2 of them belong to 1 table.
company:
id
company_info (FK to the id of company_infos)
address (FK to to the id of addresses)
company_info:
id
company_name
owner
address:
id
country
street
number
My relations in the company model:
public function address(){
return $this->hasOne(Address::class, $this->primaryKey, 'address');
}
public function company_info(){
return $this->hasOne(CompanyInfo::class, $this->primaryKey, 'company_info');
}
(My relations do work; I can get the company with their relations in my get request.)
The only way I can think of create a new company is to create company_info and address first and pass their id's to create a new company.
How do I create those 2 models so that the company model gets those 2 models' ids by their relations?
So when I send the data from my front end to Laravel like this to create a new company, how would I make a new company based on this data that's going to fill the other 2 models?
"company_info": {
"company_name": "aCompany",
"owner": "someone"
},
"address": {
"country": "some_country",
"street": "some_street",
"number": 123
}
You would first need to create the company_info and the address data via their models (There is many ways to create a instance of the model this is just the way I prefer, other alternatives include using the new keyword then saving etc.. etc...) like:
$address = Address::create([
// Attributes
]);
// and
$companyInfo = CompanyInfo::create([
// Attributes
]);
which would then have the 2 pieces of data required for creating the Company which can be done the same way as above but set the keys to the respective $address->id and $companyInfo->id
Ex.
Company::create([
// Attributes
]);
If you need any more clarification I am more than willing to elaborate further.

Laravel 'hasMany' relationship not working, no idea why

I'm having trouble retrieving data through relationships.
My database structure (simplified):
orders:
id
user_id
product_id
order_items:
order_id
product_id
I need to get using relationships, all orders along with the items in the array.
Order model:
public function items()
{
return $this->hasMany(OrderItem::class, 'order_id', 'id');
}
Test controller:
public function test()
{
return Order::with('items')->get();
}
Result I got when accessing test():
[
{
"id": "d7baaae9-b925-4ff0-8bba-13e8e88d429b",
"user_id": "fa2a5f73-379d-4ab7-9bc5-81cdbd47f3b0",
"subtotal": "0.00",
"discount": "0.00",
"coupon_code": "0",
"total": "0.00",
"paid": false,
"refunded": false,
"created_at": "2022-07-26T16:41:50.000000Z",
"updated_at": "2022-07-26T17:51:45.000000Z",
"items": [
]
}
]
The "items" array does not exist in the orders table, it is coming through the relationship, but it comes empty. There is a record in the database relating orders with order_items, the OrderItem model is correctly accessing the database when I test. I don't know what the problem could be.
[EDIT_01]: I just found out that the problem is in the id I'm using, I'm using type Uuid (Ramsey\Uuid\Uuid\Uuid::uuid4()) for the keys of my tables, somehow it's not working, but when I testo with conventional ID works. Help-me.
I have the same issue, my fix is I add
protected $keyType = 'string';
to the table which has string id (uuid). Hope it can help
hope you found a solution, if not testing out your code sample here, and everything works fine for me,
public function items()
{
return $this->hasMany(OrderItem::class);
}
use this instead, should give you a better result
Try removing the third parameter and just use this:
return $this->hasMany(OrderItem::class, 'order_id');
This should work given your Database setup example, make sure you actually have items in your database that belong to that order you are debugging as well.

how to join indexes on elasticSearch

I have two indexes : Student
"mappings": {
"properties": {
"name": {
"type": "text"
}
}
}
}
and University having a onetomany relationship with student
how to declare mappings for university?
While you can use the Join field type here, you should really beware of trying to use Elasticsearch as a relational database. It doesn't really support joins without a big performance tax and without some limitations (indexing parent and child into the same shard).
Usually the answer would be to de-normalize the relation. For example, in this case put some of the University fields directly in the Student document, allowing you to search on them directly.

Spring Data Rest OneToMany POST JSON With Child Entity

I've been searching for an answer for this since yesterday and have not been successful in finding it.
Can you save an entity with it's child entity at the same time? From what I've seen, the way to do it is to save the entity, follow the link from the response, and add the child entity. Is there a way to post it all at once?
{
"name": "some-name",
"age": "30",
"address": {
"street": "some-street",
"city": "some-city"
}
}
In the above example we have a Person entity for example and it has a OneToMany relationship to Address entity. I know that you save Person, get the link from the response, and save Address, but it would be convenient to do it all in one shot if that's possible. I am assuming that it's not possible out of the box but figured I would ask before writing a custom controller method to handle it in one shot.
That will work for adding a new entity via POST. For editing an existing entity this would also work via a PUT request if you include all the data and expose the IDs in the JSON.
e.g.
public class MvcConfiguration extends RepositoryRestConfigurerAdapter {
#Override
public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
super.configureRepositoryRestConfiguration(config);
config.exposeIdsFor(/*Person.class,*/ Address.class);
}
}
PUT /person/123
{
//"id" : 123, prob not required
"name": "new-name",
"age": "30",
"address": {
"id": 1, //required
"street": "new-street",
"city": "some-city"
}
}
I have used when there have been multiple levels of nesting and with collections but only when child entities do not have their own REST endpoints: I am not sure if that would have any bearing on things.

Laravel 5 Eloquent model dynamically generated at runtime

I am looking to make some sort of "GenericModel" class extending Eloquent's Model class, that can load database configuration (like connection, table name, primary key column) as well as relationships at runtime based on a configuration JSON file.
My reasons for wanting this are as follows: I'm going to have a lot of database tables and thus a lot of models, but most don't really have any complicated logic behind them. I've developed a generic CRUD API and front-end interface to interact with them. Each model has a "blueprint" JSON file associated with it that describes things like its attributes and relationships. This lets me automatically generate, say, a view to create a new model and it knows what attributes I need to fill in, what input elements to use, what to label them, which are mandatory, how to validate, whether to check for uniqueness, etc. without ever needing code specific to that model. Here's an example, project.json:
{
"db_table": "projects",
"primary_key": "projectid",
"display_attr": "title", // Attribute to display when picking row from list, etc
"attributes": {
"projectid": { // Attribute name matches column name
"display": "ID", // Display this to user instead of db column name
"data_type": "integer" // Can be integer, string, numeric, bool...
},
"title": {
"data_type": "string",
"unique": true // Check for uniqueness when validating field
},
"customer": {
"data_type": "integer", // Data type of local key, matches customer PK
"relationship": { // Relationship to a different model
"type": "manytoone",
"foreign_model": "customer"
},
"user": "autocomplete" // User input element/widget to use, queries customer model for matches as user types
},
"description": {
"data_type": "string",
"user": "textarea" // Big string, use <textarea> for user input
"required": false // Can be NULL/empty, default true
}
},
"views": {
"table": [ // Show only these attributes when viewing table
"customer",
"title"
],
"edit_form": [ // Show these when editing
"customer",
"title",
"description"
],
...
}
}
This works extremely well on the front end, I don't need any more information than this to describe how my models behave. Problem is I feel like I just end up writing this all over again in most of my Model classes and it seems much more natural to have them just pull information from the blueprint file as well. This would result in the information being in one place rather than two, and would avoid extra effort and possible mistakes when I change a database table and only need to update one file to reflect it.
I'd really just like to be able to do something like GenericModel::blueprint('project.json')->find($id) and get a functioning "product" instance. Is this possible, or even advisable? Or is there a better way to do this?
Have you looked at Migrations (was Schema Builder)? It allows you to programatically build models (from JSON if necessary).
Then you could leverage Eloquent on your queries...

Resources