One To Many relationship codeigniter/datamapper
I need help on this plz :
2 tables
Service : has many Sub_Service Sub_Service : has one Service
My code :
$services = new Service();
$services->where('org_id', $org_id)->get();
$services->sub_service->get();
foreach($services as $service)
{
echo $service->title;
foreach($service->sub_service as $sub_service)
{
echo $sub_service->title;
}
}
But it doesn’t work, if I want to access sub_service i have to take it out of the first loop and do somthing like
foreach($services->sub_service as $sub_service)
{
echo $sub_service->title;
}
But this is not what I want, i want to get an a开发者_如何学Pythonrray like this one :
Service 1
—Subservice 1
—Subservice 3
Service 2
Service 3
—Subservice 2
Info i’m using DM 1.8 and CI2.
Thx for ur help
Try using the 'all' property available in datamapper objects
foreach($services->all as $service)
{
echo $service->title;
foreach($service->sub_service->all as $sub_service)
{
echo $sub_service->title;
}
}
You have to use the include_join_fields method of datamapper in order to create the relationship as you want it. In your controller, include this:
$service = new Service();
$data = $service->get();
$options['records'] = $data;
and then in your view you can do this:
if(isset($records)){
foreach($records as $service){
echo $service->title;
$subservice = $service->subservice->include_join_fields()->get();
foreach($subservise as $subservice){
if(!is_null($subservice->title)){
echo $subservice->title;
}
}
}
This will give you what you want.
精彩评论