i create sequelize table like order-detail in small letter but sequelize took this name as orderDetail in all api pages.... but in database it insert like orderdetail ...it works in localhost fine but in live server shows there is no table like orderDetail ... so how to overcome this issue
this is my migration file
module.exports = { async up(queryInterface, Sequelize) { await queryInterface.createTable('orderDetails', { }}}
this is my model
class orderDetails extends Model {
static associate(models) {
// define association here
models.order.hasMany(models.orderDetails);
}
when we use relational database we must use migrate database and seeders you must create new seeders or new migrate file for your change in your database and in migrate you must use this model for create
your_field
and in your model in your app you can use :
yourField
Related
I have a column in a postgresql database table. Currently it is of datatype INTEGER, I want to change it to JSONB datatype.
Maybe this topic can answer your question: Modify column datatype in Knex migration script
For more detail you can have a look at the knex documentation: https://knexjs.org/#Schema-alter
Knex supports you to write alter column as the way you create column. The different is that you have to use alterTable() to get alterTable builder in knex that will support modifing your database information.
Or else you can take a look at my code:
Assume that I have a previous migration run before like this:
export function up(knex) {
return knex.schema.createTable('users', table => {
table.increments('id').primary('id');
table.string('username').notNullable().unique('username');
table.string('fullName');
table.string('email');
table.string('password');
table.timestamps(true, true);
});
}
And I want to modify column email so that I will use alterTable to modify the column. Note: Keep in mind that when you do migration with knex postgresql you may be failed because of some reasons so that you should use transaction for making sure that the failure will not effect to your database. But with migration of mysql, you will no need to use this because knex mysql do support transaction while dealing with migration.
export async function up(knex) {
const transaction = await knex.transaction();
try {
await transaction.schema.alterTable('users', table => {
table.string('email').notNullable().alter();
});
await transaction.commit();
} catch (error) {
await transaction.rollback();
}
}
I've built a express.js project with a mongoDB backend using mongoose.
Since I've created the mongoose models via mongoose schemas, I was wondering if it is possible to reference to the mongoose schema definition instead of re-typing all it's contents.
I'm currently using swagger-jsdoc.
Thanks and best regards
[/EDIT]
I understand, that mongoose-to-swagger basically performs this task.
However, I have no clue how I can reference to such a generated swagger schema within my swagger-jsdoc code comments.
I had the exact same issue and how i resolved it was i made a file called swaggerSchemas where i exported all the schemas like in the following example:
export default {
user: m2s(User),
};
Where User is the mongoose model.
And finally inside your swagger jsdoc options you need something like the following:
const options = {
definition: {
...
components: {
schemas: swaggerSchemas,
},
...
},
...
};
I'm building an API using Sequelize as the ORM. I wanted to incorporate some "listeners" in the core logic to check if certain values have changed and fire off some logic based on that.
One of my main concerns atm is a pivot table between customers and users. (BelongsToMany). The relation has some extra fields in the pivot like "is_admin" or "notify_user". This describes that a user is an admin for a certain customer, and if the system should notify this user on a customers action.
My API supports PATCHING of the pivot tables' data. Now what I want to do for example is if the is_admin value changes, fire off some other logic to update foo elsewhere.
All hooks work on the base object models (User and Customer). But none of my hooks are fired on the pivot object model.
Not sure if this is supported in Sequelize.
Thanks in advance
My relations are setup like this:
private static setupCustomerRelations(sq: Sequelize.Sequelize) {
const user = sq.models['User'] || new UserRepo().getNewInstance().getModel();
const customer = sq.models['Customer'] || new CustomerRepo().getNewInstance().getModel();
const customerUsers = sq.models['customer_users'] || new CustomerUsersRepo().getNewInstance().getModel()
const machine = sq.models['Machine'] || new MachineRepo().getNewInstance().getModel()
customer.belongsToMany(user, {'through': customerUsers});
user.belongsToMany(customer, {'through': customerUsers});
// Machines
machine.belongsTo(customer, {'foreignKey':'customer_id'});
customer.hasMany(machine, {'foreignKey':'customer_id'});
}
And this customerUsers is a proper model
I've had luck with Bulk hooks on join tables. Try using beforeBulkCreate and beforeBulkUpdate on the join table's model.
CustomerUser.addHook('beforeBulkCreate', 'admin-only', async function(customerUsers) {
for (const customerUser of customerUsers) {
const user = await User.findById(customer);
if (user.isAdmin) { /* ... */ }
}
}
Obviously this is going to produce tons of queries and you should think carefully about that and how to avoid that.
I wrote a sql script and in it I created a table ;
Now I need to know ,how I can execute this script? (with which codes?)
And I have another question : where? where I must write this codes?(which folder in zend project?)
if it is possible for you please explain with an example.thanks
Creating tables in the database
Zend Framework is not supposed to be the one creating the tables, thus, my suggestion is to run those scripts in other environment.
The fastest one is, probably, the very own SQL shell, but you can use another software such as MySQLWorkbench if you are using MySQL.
Once the tables are created, the access to the tables is made this way:
Introduction
When you are using Zend Framework, you are making use of the MVC pattern. I suggest you to read what is that: Wikipedia MVC
If you read the Wikipedia link, you probably know now that the acess to the database is going to be made by the model.
Thus, if you followed the recommended project structure that Zend provides you will have a models folder under your application folder. There, you are supposed to implement the classes that will make access to the DB.
But well... you now know where to locate those classes but you will ask me: how? It's easy if you know where to search. ZF provides an abstract class called Zend_Db_Table_Abstract that has all the methods that will make your life easier talking about interaction with your database's tables. This is the class that your classes should implement.
Example
Let's suppose you've got a page in your website in which you want to show to the user a list of products of your local store. You have a table in your database called "products" in which you have all the useful information such us name, price and availability.
You will have a controller with an action called indexAction() or listAction() this action is prepared to send the data to your view and will look like:
class Store_ProductsController extends Zend_Controller_Action {
public function indexAction(){
//TODO: Get data from the DataBase into $products variable
$this->view->products = $products;
}
}
And your view file will that that products variable and do sutff with it.
But now comes the magic, you will have a class that will access to the database as I've said, it'll be like:
class Model_Store_Products extends Zend_Db_Table_Abstract{
protected $_name = 'products';
public function getAllProducts(){
$select = $this->$select()
->from(array('P'=>$this->_name),
array('id', 'name', 'price', availability));
$productsArray = $this->fetchAll($select);
return $productsArray;
}
}
And ta-da, you have your array of products ready to be used by the controller:
class Store_ProductsController extends Zend_Controller_Action {
public function indexAction(){
$model = new Model_Store_Products();
$products = $model->getAllProducts();
$this->view->products = $products;
}
}
It can be said that, since fetchAll is public function, and our select does basically nothing but set which columns do we want (it doesn't even have a where clause), in this case, it would be easier to call the fetchAll directly from the controller with no where and it will recover the whole table (all columns):
class Store_ProductsController extends Zend_Controller_Action {
public function indexAction(){
$model = new Model_Store_Products();
$products = $model->fetchAll();
$this->view->products = $products;
}
}
Thus, our function in the model is not even needed.
This is the basic information of how to access to the database using Zend Framework. Further information of how to create the Zend_Db_Table_Select object can be found here.
I hope this helps.
I am trying to generate routes from one template "tuning.blade.php"
I have a DB with 250 rows I would like to dynamically create 250 routes with one route or one controller.
I want to be able to use these URLs
laravel.dev/tuning/(field from DB row 1)
laravel.dev/tuning/(field from DB row 2 and so on)
I want to put the DB requests in tuning.blade.php so that this template can display all 250 rows using 250 different URLS
I have tried to use the first example from Laravel Docs
class UserController extends BaseController {
/**
* Show the profile for the given user.
*/
public function showProfile($id)
{
$user = User::find($id);
return View::make('user.profile', array('user' => $user));
}
}
Route::get('user/{id}', 'UserController#showProfile');
I also got some interesting search results from http://forumsarchive.laravel.io/viewtopic.php?id=9010
But alsas I always end up with a notfound exception
But I am unsure what to put in my tuning template to display anything at all. my Tuning template reside in app/views/home/tuning.blade.php
Currently I have got the error "Symfony \ Component \ HttpKernel \ Exception \ NotFoundHttpException"
Can anyone put me in the right direction of where I can find a resource to help me understand?
You said you want to be able to use these URLs:
laravel.dev/tuning/(field from DB row 1)
laravel.dev/tuning/(field from DB row 2 and so on)
You can do this by declaring a route like this:
Route::any('/tuning/{field}', 'TuningController#someMethod'); you may get/post
You shouldn't run sql queries from your view and if you want to really declare some dynamic routes for each fields from your database then you may do id right from your routes.php file, for example, assume that you have a table named tunings and that table contains some fields including id, name and some others. Now, to declare routes individually for each routes dynamically using the tuning field of table tunings you may create a method in your TuningController, something like this:
class TuningController extends baseController {
// other methods...
public function registerTuningRoutes()
{
$tunings = Tuning::all(); // Assume that you have a model Tuning
// Or you may use this instead
$tunings = DB::table('tuning')->get();
// Now loop all tunings and declare routes
foreach($tunings as $tuning) {
$url = '/tuning/' . $tuning->name;
$route_name = 'tuning.' . $tuning->name;
Route::any($url, $route_name); // You may use get/post
}
}
public function TuningMethod($tuning = null)
{
// $tuning will contain the current tuning name, check
dd($tuning);
}
}
Now in your routes.php file use something like this:
Registers route for each tuning name in database
App::make('TuningController')->registerTuningRoutes();
From your terminal/command prompt check the routes by running following command:
php artisan routes
But, I think, you don't need to do this, only one route is enough as I mentioned earlier in my answer.