I'm using the following code to insert a single register of address in the database:
$this->db->insert('address', $address);
The command above inserts with:
Inesert into table(columns) values(values)
I would like to know, is there command to insert without having to specify the field names, using CodeIgniter framework and if possible, without having to handwrite the insert sql query? Like:
Insert into table values(values)
Yes it can be done with raw sql But not on CI's db->insert function,
Why? because the function/method needs 2 parameters first is the table name and second an array of key and values where the keys is the DB table's column name and value is the column value.
Unless you create one or modify the existing function, but until that NO it cannot be done.
Try a different approach like using $this->db->query('..query ..'); where you put your own SQL
Late for party, i have tricky that with this code. With some note, just be sure <input name="..."> have same name, with field name inside your table.
<input type="text" name="field_1">
Maybe can help somebody,
Example Controller :
function post() {
if (isset($_POST['submit'])) {
$this->model_name->post_data();
redirect('to_page_view');
}
}
Example Model :
function post_data() {
unset($_POST['submit']);
$this->db->insert('table_name', $this->input->post());
}
Related
Laravel > models >
In a table I have a list of files and an attribute that can be override with a value stored on another table
file_index (id, ..., code)
file_index_override(id, file_index_id, override_code)
In the file_index model, I would like to have an attribute that take the override_code if exists and the code if not. This structure is needed to run some groupBy on it.
At the moment I did
public function getCodeAnyAttribute() {
return FileIndexOverride::whereFileIndexId($this->id)->first() ?
FileIndexOverride::whereFileIndexId($this->id)->first()->override_code : $this->code;
}
But it does a single sql order on each lines, which cost a lot!
Is there a way using the power of eloquent?
Ie, given a dataset object ds = DB[:transactions].where{updated_at > 1.day.ago} - no funny joins and stuff going on - how could I fetch the table name (:transactions) ?
If you want the first table in the dataset, you can use ds.first_source.
If you want it as a string you can do:
ds.first_source_table.to_s
If you want a symbol, just omit .to_s
Based on the example provided, I would do something like this.
ds.klass.name
That will return a string with the name of your table.
In the following code, The Users table has a related table phoneNumbers. When I retrieve a list of all users like this,
return Person::with('phoneNumbers')->get();
everything works fine. However, when I attempt to specify a list of columns to return from the Person table, the phone_number returns empty.
return Person::with('phoneNumbers')
->get(['fname','lname', 'email']);
If I add the number field or phone_number.number to the get array, then I get an error as an undefined column. What is the laravel way of handling this.
Try this:
return Person::select(['your_foreign_key', 'fname','lname', 'email'])
->with('phoneNumbers')get();
Within a project I have a database table with the following columns
I would like to be able to delete from this table all rows which have a matching SharingAgencyId and ReceivingAgencyId values that I can pass in.
What I have tried so far:
public static ICollection<SecurityDataShare> UpdateSharedEntites(long conAgency, long recAgency)
{
ICollection<SecurityDataShare> agShares = null;
try
{
using (var context = new ProjSecurityEntities(string.Empty))
{
agShares = (from a in context.SecurityDataShares
.Where(c => c.ReceivingAgencyId == recAgency && c.SharingAgencyId == conAgency)
select a);
}
}
catch (Exception ex)
{
//ToDo
throw;
}
}
My thought process was to retrieve the records where the id's matched the parameters passed in and then using a foreach loop iterate through (agShare) and remove each row followed by saving my changes. With the current implementation I don't seem to have access to any of the Delete methods.
Looking to the example above I'd appreciate any suggestions on how to remove the rows within the table that contained a value of 43 and 39 using dbContext.
Cheers
If I understand right, your DbContext's properties, like SecurityDataShares should be typed as IDbSet<SecurityDataShare>. If that's correct, you should be able to use this Remove method.
foreach(var agShare in agShares) {
context.SecurityDataShares.Remove(agShare);
}
context.SaveChanges();
Be aware that this creates a separate SQL statement for deleting these objects. If you expect the number of objects to be rather large, you may want to use a stored procedure instead.
Entity Framework doesn't make it easy to run a single command to delete multiple rows (that I know of). My preference is to run a SQL statement directly for multi-entity updates/deletes using native sql with the dbcontext of sorts.
you can also pass datatable to the stored procedure with database contain dynamic type table of your type and
use that table into stored procedure for deleting matching rows from Database table.
how can I build a table of "orders" containing "IdOrder", "Description" and "User"?... the "User" field is a reference to the table "Users", which has "IdUser" and "Name". I'm using repositories.
I have this repository:
Repository<Orders> ordersRepo = new OrderRepo<Orders>(unitOfWork.Session);
to return all Orders to View, I just do:
return View(ordersRepo.All());
But this will result in something like:
IdOrder:1 -- Description: SomeTest -- User: UserProxy123ih12i3123ih12i3uh123
-
When the expected result was:
IdOrder:1 -- Description: SomeTest -- User: Thiago.
PS: I don't know why it returns this "UserProxy123ih12i3123ih12i3uh123". In Db there is a valid value.
The View:
It is showed in a foreach (var item in Model).
#item.Description
#item.User //--> If it is #item.User.Name doesn't work.
What I have to do to put the Name on this list? May I have to do a query using LINQ - NHibernate?
Tks.
What type of ORM are you using? You mention "repositories" but does that mean LinqToSql, Entity Framework, NHibernate, or other?
It looks like you are getting an error because the User field is not loaded as part of the original query. This is likely done to reduce the size of the result set by excluding the related fields from the original query for Orders.
There are a couple of options to work around this:
Set up the repository (or context, depending on the ORM) to include the User property in the result set.
Explicitly load the User property before you access it. Note that this would be an additional round-trip to the database and should not be done in a loop.
In cases where you know that you need the User information it would make sense to ensure that this data in returned from the original query. If you are using LinqToSql take a look at the DataLoadOptions type. You can use this type to specify which relationships you want to retrieve with the query:
var options = new DataLoadOptions();
options.LoadWith<Orders>(o => o.User);
DataContext context = ...;
context.LoadOptions = options;
var query = from o in context.Orders
select o;
There should be similar methods to achive the same thing whatever ORM you are using.
In NHibernate you can do the following:
using (ISession session = SessionFactory.OpenSession())
{
var orders = session.Get<Order>(someId);
NHibernateUtil.Initialize(orders.User);
}
This will result in only two database trips (regardless of the number of orders returned). More information on this can be found here.
In asp.net MVC the foreign key doesn't work the way you are using it. I believe you have to set the user to a variable like this:
User user = #item.User;
Or you have to load the reference sometimes. I don't know why this is but in my experience if I put this line before doing something with a foreign key it works
#item.UserReference.load();
Maybe when you access item.User.Name the session is already closed so NHib cannot load appropriate user from the DB.
You can create some model and initialize it with proper values at the controller. Also you can disable lazy loading for Orders.User in your mapping.
But maybe it is an other problem. What do you have when accessing "#item.User.Name" from your View?