To fetch column name - mysql

I am using struts2 , hibernate and MySql for my project.
I have table name TimeTable having 42 columns (all long datatype) containing course codes.
I want to search "column names" having particular course code from a particular row.
Help me please.

If you have mapped the entity in a "proper" way in hibernate, the answer is obvious:
You will have an entity called TimeTable, which have 42 relationships to Course (I bet the attribute name will be course1, course2.... course42).
The resulting HQL is simply a bunch of OR
from TimeTable t
where t.course1.code = :something
OR t.course2.code = :something .....
However, it is obviously a bad model design. You should make Timetable and Course a Many-To-Many relationship, and have another table storing the relationship. So, in the entity, you will see something like
class TimeTable {
#ManyToMany
private List<Course> courses;
}
Your life will be much easier with such design.

Related

Laravel Eloquent - auto-numbering on has many relationship

I'm very much a beginner when it comes to database relationships hence what I suspect is a basic question! I have two database tables as follows:
Projects
id
company_id
name
etc...
rfis
id
project_id (foreign key is id on the Projects table above)
Number (this is the column I need help with - more below)
question
The relationships at the Model level for these tables are as follows:
Project
public function rfi()
{
return $this->hasMany('App\Rfi');
}
RFI
public function project()
{
return $this->belongsTo('App\Project');
}
What I'm trying to achieve
In the RFI table I need a system generated number or essentially a count of RFI's. Where I'm finding the difficulty is that I need the RFI number/count to start again for each project. To clarify, please see the RFI table below which I have manually created with the the 'number' how I would like it displayed (notice it resets for each new project and the count starts from there).
Any assistance would be much appreciated!
Todd
So the number field depends on the number of project_id in the RFI table. It is exactly the number of rows with project_id plus one.
So when you want to insert a new row, you calculate number based on project_id and assign it.
RFI::create([
'project_id' => $project_id,
'number' => RFI::where('project_id', $project_id)->count() + 1,
...
]);
What I understood is that you want to set the value of the "number" field to "1" if it's a new project and "increment" if it's an existing project. And you want to automate this without checking for it every time you save a new row for "RFI" table.
What you need is a mutator. It's basically a method that you will write inside the desired Model class and there you will write your own logic for saving data. Laravel will run that function automatically every time you save something. Here you will learn more about mutators.
Use this method inside the "RFI" model class.
public function setNumberAttribute($value)
{
if(this is new project)
$this->attributes['number'] = 1;
else
$this->attributes['number']++;
}
Bonus topic: while talking about mutators, there's also another type of method called accessor. It does the same thing as mutators do, but just the opposite. Mutators get called while saving data, accessors get called while fetching data.

Yii2 is there a way to specify tablename in ActiveQuery conditions (like andWhere) in a nice and short way

I make a query (with \yii\db\ActiveQuery) with joins, and some fields in "where" clause become ambigous. Is there a nice and short way to specify the name of the current model`s (ActiveRecord) table (from which one the ActiveQuery was instantiated) before the column name? So I can use this all the time in all cases and to make it short.
Don't like doing smth like this all the time (especially in places where there're no joins, but just to be able to use those methods with joins if it will be needed):
// in the ActiveQuery method initialized from the model with tableName "company"
$this->andWhere(['{{%company}}.`company_id`' => $id]);
To make the "named scopes" to work for some cases with joins..
Also, what does the [[..]] mean in this case, like:
$this->andWhere(['[[company_id]]' => $id]);
Doesn't seem to work like to solve the problem described above.
Thx in advance!
P.S. sorry, don't have enough reputation to create tag yii2-active-query
to get real table name :
Class :
ModelName::getTableSchema()->fullName
Object :
$model::getTableSchema()->fullName
Your problem is a very common one and happens most often with fields liek description, notes and the like.
Solution
Instead of
$this->andWhere(['description'=>$desc]);
you simply write
$this->andWhere(['mytable.description'=>$desc]);
Done! Simply add the table name in front of the field. Both the table name and the field name will be automatically quoted when the raw SQL is created.
Pitfall
The above example solves your problem within query classes. One I struggled over and took me quite some time to solve was a models relations! If you join in other tables during your queries (more than just one) you could also run into this problem because your relation-methods within the model are not qualified.
Example: If you have three tables: student, class, and teacher. Student and teacher probably are in relation with class and both have a FK-field class_id. Now if you go from student via class to teacher ($student->class->teacher). You also get the ambigous-error. The problem here is that you should also qualify your relation definitions within the models!
public function getTeacher()
{
return $this->hasOne(Teacher::className(), ['teacher.id' => 'class.teacher_id']);
}
Proposal
When developing your models and query-classes always fully qualify the fields. You will never ever run into this problem again...that was my experience at least! I actually created my own model-gii-template. So this gets solved automatically now ;)
Hope it helped!

Recognize laravel's relationships

I got 3 linked tables and i am quite lost with eloquent relationship.
I need help to recognize my relationship type. I use Laravel 4.1
acquisitions table :
#id
date
sensors table :
#id
name
acquisition_sensor table:
#id
acquisition_id
sensor_id
depth
value
Indeed 1 acquisition may have many depth, and different values.
I search a way to link my tables and use sensor model likee:
Sensor::find(1)->acquisitions->count();
and
Sensor::find(1)->sensor_acquisition->get();
I actually do it with the Query Builder but i think there is a way to use it more efficiently with eloquent !
You are going to want to set up a many-to-many relationship in your Eloquent models.
Sensor.php (model)
public function acquisitions()
{
return $this->belongsToMany('Acquisition', 'acquisition_sensor', 'acquisition_id', 'sensor_id');
}
Acquisition.php (modal)
public function sensors()
{
return $this->belongsToMany('Sensor', 'acquisition_sensor', 'acquisition_id', 'sensor_id');
}
You can read more about many-to-many Eloquent relationships here, http://laravel.com/docs/eloquent#many-to-many
If you want to run the eloquent query you described in your question, then you can do it like so:
Sensor::find(1)->acquisitions()->count();
If you are chaining, then make sure to add the () to acquisitions.

entity framework - inheritance

I have Entity Framework Models similar to :
Category
Content
NewsCategory (Inherits Category)
News ( Inherits Content)
I use TPH inheritance for both newscategory and news . I have a TYPE field in my DB. if type=1 means News ( in content table) and again if type=1 means ( in NewsCategory table).
category and cntent have many to many relationship!
but when I want to add news how can I prevent to add news with other type ?
when I add a news it want categoryId and I can use 1,2 or other Id!
#
if fact I want to create many to many relation ship between news and news category AND category and content . and I want news dont know any thing about content and its relation ship
Database doesn't understand meaning of TPH inheritance - it has many-to-many association between Categories and Contents table and it indeed allows creating relation between any category and content. You cannot avoid it in TPH on database level but on entity level you should have navigation properties only in your derived types so handling it on application level should be straight forward.
I tend to define enums to accompany the inheritance classes I define.
public enum CategoryType
{
News = 1,
Photography,
PopularMusic
}
public enum ContentType
{
Article = 1,
Image,
Video
}
You two tables could have a TypeId and so when your code writes a news item.
Category.TypeId = (int)CategoryType.News;
and
Content.TypeId = (int)ContentType.Article;
You can't avoid having to do this is code, but it should be clearer and less error prone that just throwing an INT value at a typeId filed.
In your case I'm not sure of your relationships, such as where the Type field is (I assumed there'e one in Category and also one in Content). You seem to have missed something when you wrote type=1 means ( in NewCategory table) in you question.
I'm not sure why you would need to add a categoryId when adding a news as news inherits from Content and not Category did you mean TypeId?

Multilingual text fields with SQLAlchemy

I am currently evaluating SQLAlchemy for a project. Here is my schema:
a LANGUAGE table, with a row for each language supported
a TRANSLATION table with (ID, LANGUAGE_ID, STR)
various tables will, instead of storing text, store TRANSLATION_IDs, for example, BOOK(ID, TITLE_TRANSLATION_ID, ABSTRACT_TRANSLATION_ID)
Now, assuming each request has the current language ID available (for example, through a thread variable...), I would need SQLAlchemy to automatically join the TRANSLATION table, and thus have text fields in the current language. Something like:
class Book(Base):
id = Column(Integer, primary_key=True)
title = TranslatableText()
abstract = TranslatableText()
When retrieving, the ORM would automatically join to the TRANSLATION table with the current language ID, and my_book.title would give me the title in the current language.
I also need this to work across relations: if a class contains foreign keys to other classes that also contain translatable text fields, I would ideally like those to be retrieved too.
Lastly, I would also need to be able to get to the TRANSLATION_ID for each field, for example through my_book.title_translation_id.
I am not expecting a complete solution, but I'd like to know if something like this is feasible, and where to start.
You have to use the concept of http://docs.sqlalchemy.org/en/latest/orm/extensions/declarative.html#mixin-and-custom-base-classes
Create one top level class and write some funciton like read, write and create. Always call that function to create or read data from the database.
If you dont want to implement the mixin classes then also you can use event http://docs.sqlalchemy.org/en/latest/orm/events.html#sqlalchemy.orm.events.MapperEvents.translate_row