Adding columns dynamically to column list - php

i've built an correct working query with the query builder.
But now, there is a condition, where a method (that is responsible to dynamically ad some tables to the query) must add a columns to the query.
i've tried the following (it's much more complex, but its almost the same):
$querybuilder->select('EntityA.Property')
->from ('EntityA');
// here is happening some awesome stuff... ;-)
// Now i have to add the Table, and The column
$querybuilder->innerJoin('EntityB'); // this is working
$querybuilder->add('select', 'EntityB.Property'); // overwrites my columnlist
// $querybuilder->select('EntityB.Property'); // also overwrites my columnlist
thanks in advance

Why do you not just assemble the select-clause seperately like this:
$fields = array();
$fields[] = "EntityA.Property"
// code here, and finally, you decide you need EntityB
$fields[] = "EntityB.Property"
$querybuilder->innerJoin('EntityB');
// done with building the query, assign select
$querybuilder->select($fields);

Related

storing array data in database using laravel

I want to store the array data in a database, but in my database I'm getting only the first input tag of the form:
here is my controller:
public function store(Request $request)
{
$qt = Qt::all();
$Itemname = $request->input('Itemname');
$Quantity = $request->input('Quantity');
$Price = $request->input('Price');
$Tax = $request->input('Tax');
$Total = $request->input('Total');
$GrandTotal = $request->input('GrandTotal');
$data = array('Itemname'=>$Itemname,'Quantity'=>$Quantity,'Price'=>$Price,'Tax'=>$Tax,'Total'=>$Total);
dd($data);
Qt::table('qts')->insert($data);
return redirect()->route('quotes.index');
}
I'm not sure what you mean by 'one data' - if you are only storing one field, that shouldn't be happening. The way you have this set up, it is data for one row. Thus, the expected output to the database would be a single Qt model saved. This would be what I would expect in a store() method based on a user entering a single item (with name, price, tax, etc). One form for one new Qt. And I think you have it almost set up for this.
However, Laravel makes the storage of a new model much easier. You don't need pretty much any of that code, because it looks like you have your incoming form fields set to correctly match the name of the fields on the Qt model in the database. Though, you might want to make them lowercase on both to match convention.
If the form fields are a match to the database fields on the model, you can remove almost everything in that method and replace it with:
public function store(Request $request)
{
Qt::create($request->all());
return redirect()->route('quotes.index');
}
The create method will take the $request object as is, and automatically set the right elements to the right fields if they are set to fillable on the model.
EDIT:
I understand you are looking to make multiple rows of items for a single customer based on many items coming in through your form. However, I don't know where that information is coming from -- I don't know where the array of items is within your form (or $request object). This might be your reason why you are having an error in the first place: I don't see how to loop or find multiple items, I just see one item coming in, which would produce one row into the database based on that form. The above code is correct based on what you have said is coming from the form.
However, based on the parameterize() error you mention in the comments, you likely have an array somewhere that is causing the parameter issue, and which would help you to create multiple rows. You don't show what your array is, but you mention that these many items would be attached to a single customer.
Here is a possible way to do this. I will make up a few variables based on what you've said (some array to loop on, that there is a 'customer' object or similar, etc.)
public function store(Request $request)
{
$customer = Customer::find($request->get('customer_id'));
// I don't know how you bring in the customer's id - maybe as a $request item or perhaps through GET?
$newItemsArray = []; // Store the rows of new items here
// Whatever the array of items is, pull it and loop on it to create rows of items:
foreach($request->get('someItemsArray') as $newItem){
// Assuming the name of the array fields match the database field names:
// Assumes $newItem is an associative array
$newItemsArray['Itemname'] = $newItem['Itemname'];
$newItemsArray['Quantity'] = $newItem['Quantity'];
$newItemsArray['Price'] = $newItem['Price'];
$newItemsArray['Tax'] = $newItem['Tax'];
$newItemsArray['Total'] = $newItem['Total'];
}
// Here is where you can create all the rows and attach them at the same time to your customer
$customer->Qts()->createMany($newItemsArray);
return redirect()->route('quotes.index');
}
This will allow for creating multiple rows of items and attach to a customer all at once.
You'll need to fill in the blanks - how are you sending the multiple rows from your form, how are you sending the customer who is adding the items, how to deal with GrandTotal (is it an array item, or is it a single field passed from the form, based on a calculation), etc. But, this will answer your question on the controller side to get multiple rows in for a customer.

Add a count of related data to each item in a joomla MVC list view

I have a custom joomla MVC component.
The component has a table of items,
and a table of bids to deliver each item. An item can have multiple bids.
i need to show a COUNT of the bids on the items LIST view within each row of the foreach.
What is the BEST way of achieving this? I have tried adding the following to the items model but I am stumped at how to define $id for each item row.
public function getBidsByItemId() {
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('COUNT(*)');
$query->from($db->quoteName('#__table_bids'));
$query->where($db->quoteName('item_id')." = ".$id);
// Reset the query using our newly populated query object.
$db->setQuery($query);
$count = $db->loadResult();
}
Here you can see the full component/models/items.php to which I added it: http://ideone.com/yPJHRk
Grateful for help from the MVC experts out there.
The best way would probably be a JOIN. Try adding in line 83 something like the following (you'll have to adapt it to your db table structure):
// Join over the fields by field 'item_id'
$query->select('itemBids.bids AS bidsNum');
$query->join('LEFT', '#__entrusters_bids AS itemBids ON itemBids.item_id = a.item_id');
Then you'll be able to fetch the value from the object. I can't test it to be more specific to your problem so tell me if it works.
you should definently make a join, but from what I understand what you want is the bid-count? In that case you should make a group-by query, similar to what ilias is saying, but:
$query->select('count(itemBids.bids) AS bidsNum');
$query->join('LEFT', '#__entrusters_bids AS itemBids ON itemBids.item_id = a.id');
$query->group('a.id');
also notice to the reference change in the on-statement in the join,
regards Jonas

how to add condition in $model->save() using YII

<pre>
foreach($cons_name as $name){
$model = new Apps();
$model->const = $name;
$model->value =$value[$i];
$model->save();
}
</pre>
i am using this code how can i add some "where" conditions in this scenario. i am new to yii please tell me how to solve this issue. i am trying to save multiple records with the give code it is working for me but i want to add some more conditions to it.
also tell me how can i add multiple rows at a time instead of using loop
$model = new Apps(); will create a new object for your model. If you want to edit an existing row, you should fetch the corresponding row using find method.
$model = Apps::model()->find('id=1 and type = 2');
As far as I know, you cannot insert multiple rows without using any loop in PHP. What you can do is build you insert query with multiple rows separated by comma and execute it once.
like
INSERT INTO table1 (id,name) VALUES (1,'NAME1'),(2,'NAME2'),(3,'NAME3')
Because you use array with Active Record objects, you need foreach it and set necessary data for each object and then save.
You can use method ActiveRecord.updateAll();

Yii fetching records by type

I'm wondering if Yii has an efficient method for grouping items by type.
Let's say I have the following model:
Tag
------
id
name
type_id
And let's say there are 5 different types of Tags. I want to be able to display in my index all tags in sections by type_id. Is there a Yii-way of accomplishing this?
Outside a framework I would write a function such that results fetched from the DB were stored like this:
$tags[$typeID][] = $tag;
Then in each section I could do something like:
foreach( $tags[$typeID] as $tag )
{
// Here are all tags for one $typeID
}
But I'm having difficulty figuring out how to do this in Yii without:
A) looping through the entire result set first and rewriting it or,
B) running 5 different queries.
When using ActiveRecord simply specify the "index" in the DBCriteria. So in a query do:
ActiveRecordClass::model()->findAll(array('index'=>'type_id'));
That will return an assoc array that your after. TBF it probably executes exactly the same code, but this is obviously easier to use that performing it everywhere.
Assuming that your active record class is called MyActiveRecordClass, the simplest approach should be sufficient:
$models = MyActiveRecordClass::model()->findAll();
$groupedModels = array();
foreach ($models as $model) {
$groupedModels[$model->typeID][] = $model;
}
If you give more specific information about how you intend to display the grouped results it might be that a better approach can be worked out.

Monitor usage of a certain database field

I have a nasty problem. I want to get rid of a certain database field, but I'm not sure in which bits of code it's called. Is there a way to find out where this field is used/called from (except for text searching the code; this is fairly useless seeing as how the field is named 'email')?
Cheers
I would first text search the files for the table name, then only search the tables that contain the table name for the field name.
I wrote a program to do this for my own purposes. It builds an in-memory listing of tables and fields and relates the tables to the fields. Then it loops through tables, searching for the code files that contain the table names, and then searches those files for the fields in the tables found. I'd recommend a similar methodology in your case.
setting mysql to log all queries for some time might help. the queries will give you the tip where to look
brute force - set up a test instance - remove the column - and excercise your test suite.
create a before insert trigger on that table that monitors the insertion on that column.
at the same time create another table called monitor with only one column email
make that table insert the value of NEW.email field into monitor.email as well as in real table.
so you can run your application and check for the existence of any non-null value in monitor table
You should do this in PHP i would expect
For example:
<?php
class Query
{
var $command;
var $resource;
function __construct($sql_command = '')
{
$this->command = $sql_command;
}
public function setResource($resource)
{
$this->resource = $resource;
}
}
//then you would have some kind of database class, but here we would modify the query method.
class Database
{
function query(Query $query)
{
$resource = mysql_query($query->command);
$query->setResource($resource);
//Then you can send the class to the monitor
QueryMonitor::Monitor($query);
}
}
abstract class QueryMonitor
{
public static Monitor(Query $query)
{
//here you use $query->resource to do monitoring of queryies
//You can also parse the query and gather what query type it was:-
//Select or Delete, you can also mark what tables were in the Query
//Even meta data so
$total_found = mysql_num_rows($query->resource);
$field_table = mysql_field_table ($query->resource);
//Just an example..
}
}
?>
Obviously it would be more advanced than that but you can set up a system to monitor every query and every queries meta data in a log file or w.e

Categories