Getting another table's string via it's id - mysql

I have two tables, but since I can't format them here, you can check the table on this imgur img
The wildcard roles includes strings like department.* or blogger.department.*
I'm trying to create a role/permission inheritance system but i'm stuck on creating a many-to-many relationship
I've tried to use eloquent but since "wildcards" can't be/aren't a model , I can't use eloquent. So I tried to use the DB Facade but I'm not very good with SQL/DB so I've honestly got no clue on how to do this.
Here's what I need
Get the role ID (eg: admin = 1)
Get all wildcard_roles from the table role_wildcards by the Role ID
Return a collection of all the wildcard strings
Notes
It doesn't have to use eloquent, it can use the DB facade

It was actually quite simple after playing around
DB::table('role_wildcards')->where('parent_role_id', $this->id)->get();
Thought it'd be much more complicated

First of you create a relationship from role_wildcards to roles
public function role()
{
return $this->belongsTo('App\roles','parent_role_id','id');
}
then you use relationship like below
DB::table('role_wildcards')->with('role')->whereParentRoleId($this->id)->get();

Related

TypeORM: how to load relations with CreateQueryBuilder, without using JOINs?

I'm developing an API using NestJS & TypeORM to fetch data from a MySQL DB. Currently I'm trying to get all the instances of an entity (HearingTonalTestPage) and all the related entities (e.g. Frequency). I can get it using createQueryBuilder:
const queryBuilder = await this.hearingTonalTestPageRepo
.createQueryBuilder('hearing_tonal_test_page')
.innerJoinAndSelect('hearing_tonal_test_page.hearingTest', 'hearingTest')
.innerJoinAndSelect('hearingTest.page', 'page')
.innerJoinAndSelect('hearing_tonal_test_page.frequencies', 'frequencies')
.innerJoinAndSelect('frequencies.frequency', 'frequency')
.where(whereConditions)
.orderBy(`page.${orderBy}`, StringToSortType(pageFilterDto.ascending));
The problem here is that this will produce a SQL query (screenshot below) which will output a line per each related entity (Frequency), when I want to output a line per each HearingTonalTestPage (in the screenshot example, 3 rows instead of 12) without losing its relations data. Reading the docs, apparently this can be easily achieved using the relations option with .find(). With QueryBuilder I see some relation methods, but from I've read, under the hood it will produce JOINs, which of course I want to avoid.
So the 1 million $ question here is: is it possible with CreateQueryBuilder to load the relations after querying the main entities (something similar to .find({ relations: { } }) )? If yes, how can I achieve it?
I am not an expert, but I had a similar case and using:
const qb = this.createQueryBuilder("product");
// apply relations
FindOptionsUtils.applyRelationsRecursively(qb, ["createdBy", "updatedBy"], qb.alias, this.metadata, "");
return qb
.orderBy("product.id", "DESC")
.limit(1)
.getOne();
it worked for me, all relations are correctly loaded.
ref: https://github.com/typeorm/typeorm/blob/master/src/find-options/FindOptionsUtils.ts
You say that you want to avoid JOINs, and are seeking an analogue of find({relations: {}}), but, as the documentation says, find({relations: {}}) uses under the hood, expectedly, LEFT JOINs. So when we talk about query with relations, it can't be without JOIN's.
Now about the problem:
The problem here is that this will produce a SQL query (screenshot
below) which will output a line per each related entity (Frequency),
when I want to output a line per each HearingTonalTestPage
Your query looks fine. And the result of the query, also, is ok. I think that you expected to have as a result of the query something similar to json structure(when the relation field contains all the information inside itself instead of creating new rows and spread all its values on several rows). But that is how the SQL works. By the way, getMany() method should return 3 HearingTonalTestPage objects, not 12, so what the SQL query returns should not worry you.
The main question:
is it possible with CreateQueryBuilder to load the relations after
querying the main entities
I did't get what do you mean by saying "after querying the main entities". Can you provide more context?

ServiceStack.OrmLite: Inserting or updating columns that are not represented in the POCO?

I looked through the docs and I didn't find anything on this subject, but I thought I'd ask, to be sure:
Is there a way for OrmLites INSERT and UPDATE APIs to make it possible in one query, to insert/update columns that are not present in the POCO?
DateTime myTimestamp = DateTime.Now;
db.Insert<MyPoco>(myPoco, new { MyNewColumn=myTimeStamp });
or something like it?
I know that I can make a custom SQL, so either make a second query, inserting the custom columns, or write the whole thing myself, but I'd like to avoid that and let OrmLite do what it's supposed to do.
OrmLite is a typed code-first ORM where each POCO is the authoritative source which maps 1:1 to their respective RDBMS tables.
You can’t use OrmLite’s typed APIs with an unknown or dynamic schema and would need to Execute Custom SQL INSERT, e:g:
db.ExecuteSql(
"INSERT INTO page_stats (ref_id, fav_count) VALUES (#refId, #favCount)",
new { refId, favCount });

Can we fetch a table models from MySql using Nodejs ORM2 without defining all the properties/fields?

I would like to know if we can fetch a table model from MySql from Database, without defining all the properties.
I'm using Node.js ORM2
const orm = require('orm');
db.define('users', {
// donot want to specify all the properties/fields
});
Above users table has already been created in DB, so I just want to get that model and not create/specify all the properties in it.
We can do this with other ORM's like Objection.js - but can't change my current implementation.
Thanks in advance,
Unfortunately, you must define properties/fields while you are defining your Models. There aren't any other options.

SailsJS: Many-to-Many association in MySQL

I've tried to search before posting this question, but no success.
I'm having some troubles trying to understand the best way to achieve a many-to-many association in SailsJS.
Ex:
Hospital has many specialties
Specialty has many hospitals
How do I represent the tables in MySQL so the SailsJS operate on them?
I have an Hospital table and a Specialty table.
Do I have to have an Hospital_Specialty (not sure about if this is the correct tablename to use) table to handle those associations? Like:
Hospital_Specialty
id: int
hospital_id: int
specialty_id: int
I've read the documention but no luck on getting a proper way to achieve what I need.
Thanks in advance
Edit: My initial answer was totally wrong.
The documentation for setting up many <-> many relationships is here:
Many-to-Many | Sails.js
First of all, you'll want to work in Waterline rather than mysql to get this to work properly.
You can set up a many relationship in your model like so:
Specialty.js Model
module.exports = {
attributes: {
hospitals:{
collection: 'hospital',
via: 'specialties'
}
}
}
Hospital.js Model
module.exports = {
attributes: {
specialties:{
collection: 'specialty',
via: 'hospitals'
}
}
}
This will set up the required intermediate tables.
Up to you if you want to use plurals or not.

How to get the model name from the table name in CakePHP

In one of my projects, I have a function :
public function select($table){
$model=Inflector::singularize($table);
$result=$this->$model->find('all'));
...........
...........
}
Here, I tried to get the Model name from the given "table name"($table), and used find function of that model to select all data from that table. But that didn't work.
So, what should I do here ? Can anybody please help me ?
Thanks
You can use my trick. create table name as per model name, or using substr() or strstr() you can extract table prefix, then you can use your model ,
$tableName="myprefix_posts";
$dynamicModelName=strstr($tableName,"myprefix_");
$this->loadmodel($dynamicModelName);
if( $this->$dynamicModelName->save($this->data)){
// your code
}
You can use the Inflector class for the table name to be singularized. Example:
$dynamicModel = Inflector::singularize($table);
When you want to use the model via $this->Model you have to load it first.
$this->loadmodel($dynamicModel);
Just a friendly warning: Try not to use words that might be keywords in PHP or MySQL as variable or function names like you do in the function above (select). You or any other developers might get confused at later stages of development. There is probably no harm, I just don't recommend it.
Enjoy