CodeIgniter Many-to-Many Relationship Management - codeigniter

Can anyone point out a good many-to-many database tutorial for CodeIgniter.
Just trying to work out the process of creating, and then updating a many-to-many relationship. My example uses a multi-select of values, wondering how you take care of monitoring changes on update etc.

I'd like to share what I do in my application. This is basically same with my answer in this question.
After user submit, and before entering to database, I will fetch the existing data in the database into an array. Example: $collection = array('111', '112', '113', '114'); (This is just for example. In real, it should fetch from database then put the value to array)
I will check the new user input in two step. First step is to see if it already in the database or not. If it not, then insert. Otherwise ignore:
foreach ( $inputs as $input )
{
if ( ! in_array($input, $collection) )
{
//do insert here
}
}
Then in second loop, I do it in reverse, to delete the data that not selected by user.
foreach ( $collection as $data )
{
if ( ! in_array($data, $inputs) )
{
//do delete here
}
}
In your case, you might or might not need the second loop. I needed this since I make the input as checkboxes, that the user can choose to activate / deactivate, thus I translate it as insert and delete.
Since you will implement it using multi-select, then basically it's same with my checkboxes.
If you have structure or code example, feel free to share it, and I will help you fine tune it (of course with my style, that might or might not optimized yet).

This website has some tutorials for many to many. It uses doctrine though.
http://www.phpandstuff.com/articles/category/tutorials

The codeigniter from scratch series will cover almost anything you want to know about the framework
http://net.tutsplus.com/videos/screencasts/codeigniter-from-scratch-day-1/
hope that helps. there are 7 to date btw

Related

laravel 5.2 work with belongs to with two different queries

I have write down this query
Controller
$data = User::where('name',$name)->with('country');
In User model
function country () {
return $this->belongsTo('App\Country');
}
In view
echo $data->country->name;
It is working fine but it run 2 queries :(
Select * from user where name = "xyz"
Select * from country where id = "745"
I want to stop this, I want to fetch data with one query only. Join is the solution, Is any other solution for this?
Unfortunately this is the way Eloquent works. It uses two queries because it's a simpler task to initialise your models and to avoid column naming conflicts.
If you are concerned about performance but still want some sort of querying tool, use the Query Builder shipped with Laravel.
To answer your question, joins will be your best bet.
$data=user::with('country')->where('id',745)->where('name','xyz')->get();
i hope that will help you

Laravel : Delete all records that are not in array

I have a datepicker calendar in my views, and basically I need to synchronize the selected dates (that I send in ajax) with a BoxDeliveryDate model (which only has one column named "date").
So in my Controller I was able to write a pretty nice method to only create a new record if one the selected dates is not yet stored in the database, like this :
foreach (Request::get('dates') as $date) {
$date_formated = date('Y-m-d', strtotime($date));
BoxDeliveryDate::firstOrCreate(['date'=>$date_formated]);
}
Now, if the user de-select one the dates in the datepicker, later, and synchronize, I need to delete it from the database.
Is there a nice way to do that in Laravel ? In other words, to delete every record of the table that are NOT in my Request::get('dates') ?
Also, I searched for a simple way to synchronize everything with only one method, but couldn't find anything.
Thanks for helping !
You can use whereNotIn() for that:
BoxDeliveryDate::whereNotIn('date', Request::get('dates'))->delete();
Note that this will not trigger any model events nor will it work with soft delete. Also, depending on the format of dates you might have to format the array before passing it to whereNotIn().
Also I believe it should be Request::input('dates') but it's possible that both actually works...
I would highly recommend using the soft delete trait (built into Laravel) if your doing mass deletes!
http://laravel.com/docs/4.2/eloquent#soft-deleting
$this->model->whereNotIn('id', $ids)->delete();

Update, Insert, Delete records Joomla Table

I'm able to fetch information for whatever table I need the problem here is the update, insert, and delete records, is not working..
I have read the Joomla doc's but even doing the simplest update queries are not working... so here is my code:
UPDATE:
// I'm getting the data from an array
if (!empty($_POST['data'])) {
$getData = json_decode($_POST['data'], true);
}
// after this line I have a foreach for the array
// in the foreach I have a few IF's
// ether if the result from IF is True or False
// in both I have similar queries
// So let say IF return true;
// Lets prepare the Data using OBJECT's
$object = new stdClass();
$object->product_id = $v['product_id'];
$object->product_name = $v['product_name'];
$object->product_price = $v['product_price'];
$object->product_number = $v['product_number'];
$result = JFactory::getDbo()->updateObject('#__tienda_product', $object, 'product_number');
// that should Update my tables but it doesn't ... now my table has about 21 columns
// but I only need to update 4 columns base on the column product_number
You might have notice the $v['product_id'] where $v is from the foreach, the foreach and the first query are working fine, I did a few echo's before moving to the Update part just to make sure I'm getting the correct data in a format that it should be... any way... the Update part is not working... so I thought it may be because of my table I when to use one table from the regular instalation of joomla... but it still the same no result on the update...
Does any one know how to "update" a table using Joomla CMS as framework?...
Remember I want to use the updateObject() method...
Why don't I use Joomla Framework instead of the CMS's library?
Well, I can give you a few examples, let say:
a business man want a simple basic report, he doesn't care about managing the site he has people to do that, he also gets a sales report, but he doesn't trust the crew just yet and he want to able to see and compare the result, and he needs and standalone without all the fancy tools that joomla has and for that he need an standalone app that can give that kind of report... ok I might have gone a bit far, but the idea is to have basic, simple, easy to read reports and updates, and that is why I have started this project.
Again, I already went to joomla and read the docs but following their examples it just not working... now, am I have to declear all of the columns even if they don't need to be update? or am I missing an execution for the query which in joomla doesn't mention any executions when using $object() only when using regular queries SQL... the idea is to use $object() ...
Thank you for taking the time.
You have defined the updateobject as a variable, and are not calling it. try changing this:
$result = JFactory::getDbo()->updateObject('#__tienda_product', $object, 'product_number');
to this:
JFactory::getDbo()->updateObject('#__tienda_product', $object, 'product_number');
Also, on a side note, you should not use $_POST and instead should use JInput

Codeigniter and nested tab markup

I need some guidance. Forgive me for a lengthy post but I need to explain myself. In my world, there is no one who understands what I am talking about so I have to go online for assistance.
I am an architect doing my own website because work has dried up and I plan to use an improved website for a marketing campaign.
I have done what I'd call a "lash-up" of this site which functions OK. But it's nowhere near ready to publish. I am trying to get it reorganised to do this and am moving the whole thing over to Codeigniter. My puzzle relates to views in Codeigniter.
One of the main pages for potential clients is the projects page showing work done. It uses nested tabbing. As I have said, I've made it work OK in ordinary procedural PHP.
Note that the projects are organised by category i.e housing, commercial etc In each category there are projects.
Actually the tabs are dynamically produced with some assistance from jQuery. I mean by this that my homespun php creates markup based on what's returned from the database.
The tab markup is the usual one of an unordered list whose li elements contain anchors whose hrefs reference divs arranged below. To achieve nesting, these divs then contain another ul with a further set of divs related to it.
The top tabs correspond to a category e.g housing, commercial. The lower tabs correspond to projects within a category.
I've made this work with four queries before. I think at least one may be redundant but I said it was a "lash-up".
Query 1: "select distinct pcat, pcatid from pcategory inner join projects on pcatid = projcat order by pcat desc"
From this query I get hold of the id used in the href.
Query 2 : same as above but this time the id is used for div id.
The next query is the source of my puzzlement because I don't see how to replicate it with CI.
Query3 :
$jobcat=$row2['pcatid'];
$queryall3 = "select projid, projtit, projcost, projdate from projects where projcat= '$jobcat'";
This query uses the category id - $jobcat - returned by each iteration of the while clause used to expand the results from query 2. In other words, it runs inside the query 2 while loop so it can get the category id and then get all the projects related to it.
The results of query 3 are used to form the lower tabs, and their href value is the id of the project.
Query4: same as query 3 and used to populate the lower divs with data from the database relating to a specific project.
So, finally my question: it seems to me that query 3 is difficult to manage using the Codeigniter set up. I can imagine an array of results looped over in a view. What I can't conceive is how to make a model call within that loop.
Apologies for a long-winded question and any maladroit coding assumptions exhibited. Assistance would be a blessing.
Tom
I don't really see what you're asking, but it seems that you want to know how to perform queries in CI?
In which case I suggest you take a good read of the docs
$this->db->select('pcat, pcatid');
$this->db->distinct();
$this->db->from('pcategory');
$this->db->join('projects', 'pcategory.pcatid = projects.pid', 'inner');
$this->db->order_by('pcat', 'DESC');
$result = $this->db->get();
I very much doubt this will work as I do not know your table structure but may give you an idea of how to use the active record class in CI.
You can of course just use the query method:
$results = $this->db->query('YOUR QUERY HERE');
the active record class can do a lot of the work for you, however.
As for about being difficult to do in CI, this is simply untrue - you just need a clearer picture and understanding of what you want to achieve.
Edit
$jobcat=$row2['pcatid'];
$queryall3 = "select projid, projtit, projcost, projdate from projects where projcat= '$jobcat'";
$results=$this->db->query($queryall3);
$data = $results->result_array(); // get the results of the 3rd query as an array
// new query
$this->db->select('query_4_select'); // select whatever you need
$this->db->from('whatever_table');
// this probably isn't the most efficient way, but for examples sake:
foreach($data as $row) // using the result_array from above
{
$this->db->or_where('query_4_id', $row['id']); // the magic !!
}
$new_results = $this->db->get();
So essentially, you get the ID's from query 3, run it through a foreach and build a where x=x or x=y or x=b type query, which will then (hopefully) return the desired results.
This is one way, you will need to tweak it.
But it sounds like you can just use a join? Perhaps if you could post your entire tables structure.

Codeigniter--How do store info? (noob)

I'm building my first real CI app. I have to build a survey system--If the specifics are important, I'll elaborate.
What is the best way to post the info to the db from the user? In a single row, comma separated? I'm a noob here, so detail would be appreciated! :)
I should add: the user needs to have the ability to try multiple times for the test and have each test's score charted. Payment is required to take each test.
Here's where I'm at. This code works, but I'm sure there's a more elegant way to do things.
$this->db->select('credits')->from('be_user_profiles')->where('user_id', $this->session->userdata('id'));
$query = $this->db->get();
foreach ($query->result() as $row)
{
echo $row->credits;
}
What about this?
That's more like a code organization / code structure question than a problem.
You can fetch your input data "by hand" or use Active Record CI library to do that (https://www.codeigniter.com/userguide2/database/active_record.html#insert)
If CI has ORM implemented, the job should be even easier than this.
Just create a controller and check the input data on it (or inside the model) and create a model to apply the necessary cleanups, data verification and proper data assign to one or mode tables and you're set.
edit : more elegant than the example you've showed would be with ORM, but I'm not sure CI has that implemented yet.
It depends on how the data is structured, but your best bet would be to have a survey table, and store the answer to each question in a different column.
From an MVC point of view, you would have a form in a view, have the controller pass the data from that form the model when it is submitted, then have the model clean the data and insert it into the database.

Resources