I set up an many to many relationship between Orders and Sets. An Order can contain many Sets and different Sets can belong to different Orders. Because you can set the amount for a set in a order there should be an additional column for amount.
So e.g. an Order can consist of 5 x "Set A" and 10 x "Set B".
This is the schema of the join table:
OrderSet:columns:
amount: integer
order_id:
type: integer
primary: true
set_id:
type: integer
primary: true
Works fine so far, I just donĀ“t know how I can set the value of the amount column.
This is how I save the order / set-order relationship:
public function saveOrder($data){
$tempSets = $data->sets;
$order = new Order();
unset($data->sets);
$order->merge((array) $data);
foreach($tempSets as $set){
$q = Doctrine_Query::create()
->from('Set s')
->where('s.id = ?', $set->id);
$set = $q->fetchOne();
$order->sets->add($set);
}
$order->save();
}
How can I set the amount of each set?
Many to many thanx for your help.
cheers, Florian
ah i found this post:
NHibernate: Many-to-many relationship with field in the relationship table
they say... treat the relation table as entity.
now thats the way it works:
public function saveOrder($data){
$tempSets = $data->sets;
$order = new Order();
unset($data->sets);
$order->merge((array) $data);
$order->save(); //save order first to make the order id available
foreach($tempSets as $set){
$orderSet = new OrderSet(); //create an object of the Class representing the relation table
$orderSet->order_id = $order->id;
$orderSet->set_id = $set->id;
$orderSet->amount = $set->amount;
$orderSet->save();
}
}
hope that can help someone else too.
cheers,
florian
Related
I am try to add id from one table to another table to give a relationship to the tables.
i have 2 table ..
classes.(id,cls,divn)
id cls divn
1 1 A
2 1 B
4 2 A
5 2 B
6 2 C
7 3 A
2.teacher(id teachername,tclsid,tsub)
Now i want ,im enter teachername and select class,division ,subject on select box using html tag.
if im select class and division check to classes table.and get id from selected class & division to insert into teacher table tclsid feld.
how its possible??
im trying to select multiple class and division
im using controller.php is here
$clss =implode(',', Input::get('tcls'));
$divn =implode(',', Input::get('tdivn'));
$teachers =new ForumTeacher();
$teachers ->tname=Input::get('tname');
$teachers->tmobile=Input::get('tmobile');
$teachers ->ttype=Input::get('ttype');
$teachers ->tsubject = implode(',', Input::get('tsubject'));
$cs = ForumClass::where('cls', $clss)->where('divn', $divn )->first();
$teachers->tcls= $cs->id;
but not work this code $teachers->tcls= $cs->id;` ...
i want teacher table like this
id teachername tclsid tsub
1 xyz 1,5 maths
2 poq 5,7 english
if xyz teacher select class &division are 1,2 & A,B(so id is 1,5)
if poq teacher select class &division are 2,3 & B,A (so id is 5,7)
but i got an error
ErrorException (E_UNKNOWN)
Trying to get property of non-object
error code line is
$teachers->tcls= $cs->id;
Your $teachers var is holding a new, unsaved ForumTeacher model. You have not assigned the tcls value in $teachers. So the $teachers['tcls'] is not set, Add:
$teachers->tcls = $cs->id;
I don't understand what your are trying to do with:
$clsid[$cs->id] = $teachers['tcls'];
If you set the tcls attribute of $teachers first, what you are doing is the same as:
$clsid[$cs->id] = $cs->id;
Don't forget to save the model when you are done setting its attributes:
$teachers->save();
Get id from one table an add another table in laravel 4
$cs = ForumClass::where('cls','=', $clss)->where('divn','=', $divn )->first();
$teachers->tcls= $cs->id;
Reread your question and code and from what I understand you are getting multiple class, division combinations and subject for multiple teachers. You either have to have one teacher and one cls and one divn and one subject or the same number of these corresponding to different teachers. Otherwise, I am confused by your model, so I am assuming you have one of each per teacher instance.
Then you need to iterate over the inputs and create one teacher at a time or create an array and batch create them. I'll do the iteration for simplicity of following it:
// assuming all input arrays have the same count() of elements and
// are all in the same order
$tclss = Input::get('tcls');
$tdivns = Input::get('tdivn');
$tnames = Input::get('tname');
$tmobiles = Input::get('tmobile');
$ttypes = Input::get('ttype');
$tsubjects = Input::get('tsubject');
$iMax = count($tclss);
for ($i = 0; $i < $iMax; $i++)
{
$tcls = ForumClass::where('cls', $tclss[$i])->where('divn', $tdivns[$i])->get();
if (is_null($tcls))
{
// cls, divn combination is missing from your table
// if you want to add it then do so or handle the error
$tcls = new ForumClass();
$tcls->cls = $tclss[$i];
$tcls->divn = $divns[$i];
$tcls->Save();
}
$teacher = new ForumTeacher();
$teacher->tname = $tnames[$i];
$teacher->tmobile = $tmobiles[$i];
$teacher->ttype = $ttypes[$i];
$teacher->tsubject = $tsubjects[$i];
$teacher->tcls = $tcls->id;
$teacher->save();
}
I did not test this but you get the idea of what to do.
I have three tables; user, car and user_x_car. user_x_car holds users who own car; user_id and car_id are stored. I want to get users who don't own a car as follows:
$car_owner = $this->db->select()->from('user_x_car')->get()->result();
for ($i = 0; $i < count($car_owners); $i++)
$car_owner_id[$i] = $car_owner[$i]->user_id;
$non_car_owner = $this->db->select()->from('user')->where_not_in('id', $car_owner_id)->get()->result();
I get what I want, however, is there any way to bypass the for loop in the middle which creates and array of id's selected in the first select. Is there any way to get array of selected user_ids directly?
you can do it by two queries like
first one get all ids from user_x_car table
$temp1=array();
$temp=$this->db->distinct()->select('user_id')->get('user_x_car')->result_array();
then from user table fetch those users who have no cars
foreach($temp as $each)
{
array_push($temp1,$each['user_id']);
}
$rs=$this->db->where_not_in('id',$temp1)->get('user');
if($rs->num_rows()>0)
{
$data=$rs->result_array();
print_r($data);die;
}
$data will print all users who have no car. Please let me know if you face any problem.
function get_unread_notifications_ids()
{
//get unread notifications ids
$this->db->select('GROUP_CONCAT(fknotification_id) as alll');
$this->db->from("te_notification_status_tbl");
$this->db->where('read_status',0);
$ids=$this->db->get()->row();
return $idss=str_replace(",","','",$ids->alll);
}
and second function like this:
function get_unviewed_photos_events(){
$idss = $this->get_unread_notifications_ids();
$this->db->select('img.*',False);
$this->db->from("te_notifications_tbl notif");
$this->db->join('te_images_tbl img','img.id=notif.reference_id','LEFT OUTER');
$this->db->where("notif.id IN('".$idss."')");
$rslt = $this->db->get()->result_array();
return $rslt;
}
Query
$non_car_owner = $this->db->query('SELECT user.*
FROM user LEFT JOIN user_x_car ON user_x_car.id=user.id
WHERE table2.id IS NULL')->result();
Here users who are not on the table user_x_car
foreach($non_car_owner as $user){
echo $user->user_id;
}
I wanted to know how to check whether there is a value present in a table (managers) and then add a 'yes' or 'no' string depending on if there is a value in that table or not.
$this->db->select('employees.first_name, employees.last_name, departments.department_name, departments.department_numb, titles.title');
$this->db->from('employees');
$this->db->where('first_name', $firstname);
$this->db->where('last_name', $lastname);
$this->db->join('department_manager', 'department_manager.emp_numb = employees.emp_numb', 'inner');
$this->db->join('departments', 'departments.department_numb = department_manager.department_numb', 'inner');
$this->db->join('titles', 'titles.emp_numb = employees.emp_numb', 'inner');
$this->db->where('department_name', $dept);
$this->db->where('title', $jobtitle);
$result = $this->db->get();
$data = array();
foreach($result->result() as $row)
{
$entry = array();
$entry['firstname'] = $row->first_name;
$entry['lastname'] = $row->last_name;
$entry['jobtitle'] = $row->title;
$entry['dept'] = $row->department_name;
$entry['deptid'] = $row->department_number;
//$entry['ismanager'] =
$data[] = $entry;
}
return $data;
I want to check whether an employee is present in the table 'department_manager' which is joined by an employees number. So if that employee number is not present in the table 'department_manager' then I want to insert in the array index $entry[ismanager'] a string which says 'no', and if the employee number is present in the table 'department_manager' then I want $entry['ismanager'] to hold the string 'yes'.
But I'm confused as to how to check that the employee is present or not in that table. Do I do it in the active record query or in the foreach loop? And if it is done in the foreach loop then how do I make that comparison as the query is completed?
Why have a field that is basically a calculated value? That's like having fields for quantity per box, quantity of boxes then saving the total items to a third field. Never save to the database something you can gain access to via a quick query. In your query above it's as simple as changing the dept manager join to a left join, including the dept manager id and saying if that field is blank in a record the person is not a manager. Using a LEFT join will return all records whether they have an entry in the management table or not.
Add: department_manager.emp_numb to the select.
The Join:
$this->db->join('department_manager', 'department_manager.emp_numb
= employees.emp_numb', 'left');
Then in the foreach:
if(!$row->department_manager.emp_numb)
{
this person is not a manager;
}
If you feel you really must have that extra field then you can still populate it with the method above.
If you are using MySQL, I think you are looking for:
IFNULL(expr1,expr2)
where:
expr1 == null condition (in your case NULL)
expr2 == replacement value
Source: Control Flow Functions
4 for on on my applications with Doctrine.
In there I'm using the following doctrine command to retrieve person object collection
//query
$people = $q->execute();
This return 20 objects. The primary key of the person object is a composite key with three attributes. Those are
id
department_id
name
I need to get person objects by searching in it as follows.
$id = 10;
$department_id = 1;
$name = "abc";
$people->get($id, $department_id, $name);
But this doesn't work and not give correct results. I tried with this and it gives null results which seems my collections primary key is not set.
$people->getKeyColumn();
I don't want to go through a foreach loop in collection and process it because when I deal with about 500 people, it slow down my application.
Can some one help me with this issue to get values from a doctrine collection.
Can you use something like this?
$people = Doctrine::getTable('Persons')
->createQuery()
->where('id = ? AND department_id = ? AND name = ?', array($id, $department_id, $name))
->execute();
It will get you a DoctrineCollection already filtered by the parameters provided.
'Persons' here is a Doctrine model name, not a table name from mySQL.
You can also use Doctrine's magic finders findBy*():
$people = Doctrine_Core::getTable('Persons')
->findByIdAndDepartmentIdAndName($id, $department_id, $name);
I have two tables, content and images (and a ContentImages table for the one to many relation, so that's actually 3 tables).
The following code saves the relation (in the action > updateContentFromRequest() ):
$ids = $this->getRequestParameter('contentImages');
if( isset($ids) ){
$ImagesTable = Doctrine::getTable('Content')->getRelation('Images')->getTable();
$associationName = Doctrine::getTable('Content')->getRelation('Images')->getAssociationTable()->getOption('name');
$this->content->$associationName->delete();
foreach ($ids as $id){
$id = explode('/', $id);
$this->content->get('Images')->add($ImagesTable->find($id));
}}
I changed the model to include a sort field in the ContentImages table:
content_id
image_id
sort (numeric)
The sort number is simply that, a number (0,1,2,3 etc)
$sort = $this->getRequestParameter('contentImagesSort');
How do I save the sort number? I do not want to add a sort field to the Image table because that could create difficulties when images are re-used across more content items. When a content item is new I do not know the ID yet so I'm a bit stumped...
If you have generated models you can add to your setUp method the orderBy parameter:
$this->hasMany('PICTURE as PICTURES', array(
'local' => 'BRAND_ID',
'foreign' => 'PICTURE_ID',
'refClass' => 'BRAND_PICTURE',
'orderBy' => 'your_field DESC'
));
orderBy should do the trick
You should add One to Many associations on your join Table, like:
ContentImages:
relations:
Image:
local: image_id
foreign: id
Content:
local: content_id
foreign: id
As such, you will be able to query directly the join table like this :
$q = Doctrine_Query::create()
->from('Content c')
->leftJoin('c.ContentImages ci')
->leftJoin('c.Images i')
->execute();
Then you can access to ContentImages using
$content->ContentImages->setSort('your sort');
This should do the trick :)
I do things a little a differently from what you've got above so not completely sure this is what you're asking, but can't you just save the object with whatever is needed for it?
$association = // load up existing entry from ContentImages using whatever method
$association->setSort($the_sort_I_want_to_add);
$association->save();
Or querying it...
$association = // load up existing entry from ContentImages using whatever method
$my_unknown_sort = $association->getSort();
Hope that helps.