How to get only updated row from database and make app more efficient - sql

I'm creating laravel/vue.js CRUD app and I everything works fine for now but I'm worried about quality of my queries to database after update data.
I am using getAllData() each time when I update row in the database. Now, when I have a few records in database is not a problem to ask server each time and render new list in vue but in when I will have a few thousands of rows it will make my app slow and heavy.
Now I update database like this:
This is part of my vue.js update function:
updateStatus: function(id){
var index = _.findIndex(this.rows,["id",id]);
if (this.rows[index].pay_status=="waiting"){
axios.put("http://127.0.0.1:8000/api/payments/"+id
,{pay_status:"payed"}).then((response)=>{
this.getAllData();
}
This is my vue.js getAllData function:
getAllData: function(){
axios.get("http://127.0.0.1:8000/api/payments").then((response)=>{
this.rows = response.data;
});
}
and my PaymentsController:
namespace App\Http\Controllers;
use App\Payments;
use App\Suppliers;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Faker\Generator;
class PaymentsController extends Controller
{
public function index()
{
$payments = Payments::with('suppliers')->get();
return response($payments, Response::HTTP_OK);
}
}
my updation function:
public function update(Request $request, $id)
{
$payments = new Payments();
payments::where('id', $id)->update($request->all());
}
Is thare any way to make update in more efficient way, for example get only updated row from database and put it into my existing object with rows? Or maybe i should not worried about it?

Without seeing your logic:
Your controller can return the record:
return response(['payment' => $payment], Response::HTTP_OK);
Your axios method can observe that response and then do a replace on the index (just like you did when getting the index previously)
.then((response) => {
const { payment } = response.data;
this.items[index] = payment;
})
As long as items was instantiated in data as an [] then it's observable.

If you need updated rows for particular time period.
Also, you can do one thing. When user updating the row u can store the unique ID in new table and you can fetch the data through that ID. and then you can delete that ID from new table when you don't need latest updated data.
WHILE UPDATING THE ROW via ID
insert id in new table.
update the record.
if need updated record only >> use back-end conditions as per the
requirement >> Fetch id from new table join with main table.
when you don't need that latest updated record. Delete records from
new table. >> use back-end conditions as per the requirement >>
fetch from main table.

As #Ohgodwhy said, I change my code like this and now it works fine.
update function
public function update(Request $request, $id)
{
$payments = new Payments();
payments::where('id', $id)->update($request->all());
return response(payments::where('id', $id)->get(), Response::HTTP_OK);
}
axios
updateStatus: function(id){
var index = _.findIndex(this.rows,["id",id]);
if (this.rows[index].pay_status=="oczekuje"){
axios.put("http://127.0.0.1:8000/api/payments/"+id,{pay_status:"zapłacono"}).then((response)=>{
this.rows[index].pay_status=response.data[0].pay_status;
this.waitingInvoices = this.countInvoices();
this.toPay = this.calculatePayment();
});
} else if (this.rows[index].pay_status=="zapłacono"){
axios.put("http://127.0.0.1:8000/api/payments/"+id,{pay_status:"oczekuje"}).then((response)=>{
this.rows[index].pay_status=response.data[0].pay_status;
this.waitingInvoices = this.countInvoices();
this.toPay = this.calculatePayment();
});
}
},

Related

how to use firestore query result in another query. Kotlin

Tell me please. Here is the base:
"orders" inside this base there are fields ID, number, address, and so on and there is a collection of "carpets" inside the base of carpets there are also different fields, including the field cost (that is, the cost of cleaning this carpet).
now QUESTION:
how to calculate the total cost and write the result in the "orders" database field?
in general it is interesting how to implement it. How to make such queries so that later the result obtained is already written in a different field?
A good approach for a summary field is to define a property on the parent document ("order", in the OP case) and code a write-trigger on the child collection ("order/carpets").
The trigger's job is to determine what sort of write has taken place on the collection and update the parent doc's prop accordingly.
Code something like (very roughly like) the following in your cloud functions folder...
// when carpets are written, update their parent order's "ordersTotal" prop
exports.didUpdateCarpets = functions.firestore.document('orders/{orderId}/carpets').onWrite(async (change, context) => {
const ref = db.collection('orders').doc(orderId);
try {
await runTransaction(db, async (transaction) => {
const doc = await transaction.get(ref);
let ordersTotal = doc.data().ordersTotal;
// modify orderTotal based on the trigger params
const before = change.before.exists ? change.before.data() : null;
const after = change.after.exists ? change.after.data() : null;
if (!before) ordersTotal += after.cost; // created
else if (!after) ordersTotal -= before.cost; // deleted
else ordersTotal += after.cost - before.cost; // modified
transaction.update(ref, { ordersTotal });
});
} catch (e) {
console.log("Transaction failed: ", e);
}
});

Odoo 10 - Javascript Query to a Model

I'm doing:
var callback = new $.Deferred();
new Model('pos.order').query(['invoice_id']).filter([['id', '=', '100']])
.first().then(function (order) {
if (order) {
callback.resolve(order);
} else {
callback.reject({code:400, message:'Missing Order', data:{}});
}
});
It works fine, and returns an Order object. But my issue is that i want to access the relation objects (many2many, many2one), but the order object has only the ID's of his relations. For example if i want to access the company or invoice object from the Order that i just fetched i need to do another query and i want to get all in a single query.
Use below js code to call method in py to get your required data.
new Model("pos.order")
.call("method_in_pos_order_model", [100])
.then(function (result) {
// Result is having what you want..
});
Method in Py under pos.order model
#api.model
def method_in_pos_order_model(self,id):
return self.search([('id','=',id)])
I hope this will work for you.

Remove `data` key from fractal transformed single item

I'm using fractal with lumen framework to build an API. It works great but when I return any specific item, it return the result inside a data key.
{ data : { /** All data **/ }}
I understand the use of data key in a collection. But I don't feel the necessity of having data key in single result. ( Correct me if its a wrong REST convention )
So how can I remove data key from single result?
Put this code in your Bootstrap/app.phpcan help you to avoid data. You can make it as a service provider also.
$app->bind('League\Fractal\Manager', function ($app) {
$fractal = new \League\Fractal\Manager;
$serializer = new \League\Fractal\Serializer\ArraySerializer();
$fractal->setSerializer($serializer);
return $fractal;
});
$app->bind('Dingo\Api\Transformer\Adapter\Fractal', function ($app) {
$fractal = $app->make('\League\Fractal\Manager');
return new \Dingo\Api\Transformer\Adapter\Fractal($fractal);
});

jQuery dataTables - Checking and adding new row if not exist using API .any()

I am trying to add new row in datatables, and by using the API .any() to check if the id is already exist in the rows and if it exist I will not add new row to my datatable, and here is the result form my request from databse see http://pastie.org/10196001 , but I am having trouble in checking.
socket.on('displayupdate',function(data){
var dataarray = JSON.parse(data);
dataarray.forEach(function(d){
if ( table.row.DT_RowId(d.DT_RowId).any() ) { // TypeError: table.row.DT_RowId is not a function
console.log('already exist cannot be added');
}else{
table.row.add(d).draw();
}
});
});
Thank you in advance.
You get the error, of course, because DT_RowId not is a function in the API. But DT_RowId is in fact the one and only property that get some special treatment from dataTables :
By assigning the ID you want to apply to each row using the property
DT_RowId of the data source object for each row, DataTables will
automatically add it for you.
So why not check rows() for that automatically injected id along with any()?
socket.on('displayupdate',function(data){
var DT_RowId,
dataarray = JSON.parse(data);
dataarray.forEach(function(d){
DT_RowId = d.DT_RowId;
if (table.rows('[id='+DT_RowId+']').any()) {
console.log('already exist cannot be added');
} else {
table.row.add(d).draw();
}
});
});
simplified demo -> http://jsfiddle.net/f1yyuz1c/

How to save content from yii widget to Database?

here is the ListBuilder Widget code:
$this->widget('ext.widgets.multiselects.XMultiSelects',array(
'leftTitle'=>'Australia',
'leftName'=>'Person[australia][]',
'leftList'=>Person::model()->findUsersByCountry(14),
'rightTitle'=>'New Zealand',
'rightName'=>'Person[newzealand][]',
'rightList'=>Person::model()->findUsersByCountry(158),
'size'=>20,
'width'=>'200px',
));
List Builder view this
I wanna save that entire list i select to right list on to my DB.
how to do this?
The source code is available so you just have to look in the controller:
public function actionMovePersons()
{
if(isset($_POST['Person']['australia']))
{
foreach ($_POST['Person']['australia'] as $id)
Person::model()->updateUserCountry($id, 14);
}
if(isset($_POST['Person']['newzealand']))
{
foreach ($_POST['Person']['newzealand'] as $id)
Person::model()->updateUserCountry($id, 158);
}
Yii::app()->user->setFlash('saved',Yii::t('ui','Data successfully saved!'));
$this->redirect(array('site/extension','view'=>'listbuilder'));
}
And in the model:
public function updateUserCountry($id, $country_id)
{
$model=$this->findByPk($id);
$model->country_id=$country_id;
$model->update('country_id');
}
The above updates the Person in the database and sets the new country. If I understand your question correct you want to create new entries (maybe in a different table) instead of changing existing ones. To do this you can easily modify the updateUserCountry() function to create a new Person instead of updating it.