CodeIgniter控制器中为演唱会数组关联对应场地数据的方法
Fixing CodeIgniter Concert Array Data Enrichment
Let's work through this step by step. I spot a few gaps in your current code, plus we need to handle both venue types (festivals and halls) as per your database rules. Here's how to get the desired result:
First, Diagnose the Issues
- Your existing code only handles the
Hallsassociation and ignores theFestivalscase based oncPlaceType - You weren't assigning the processed
$getConcerts_previousarray to your view data (this is probably why you didn't see the new field in your var_dump!) - We need to branch logic based on the
cPlaceTypevalue to pull the correct related data
Corrected Controller Code
public function index() { // Fetch all past concerts $getConcerts_previous = $this->concert_model->getAllConcerts('previous'); // Loop through each concert to enrich with venue data foreach($getConcerts_previous as $concert) { // Handle Festival venues (cPlaceType = 1) if ($concert->cPlaceType == 1) { $festivalData = $this->festival_model->getFestivalbyID($concert->cPlaceID); $concert->fFestival_ID = isset($festivalData) ? $festivalData->fID : 'No data'; } // Handle Hall venues (cPlaceType = 2) elseif ($concert->cPlaceType == 2) { $hallData = $this->hall_model->getHallbyID($concert->cPlaceID); $concert->hHall_ID = isset($hallData) ? $hallData->hID : 'No data'; } // Fallback for unknown place types else { $concert->venue_status = 'Unknown place type'; } } // Pass the enriched array to your view $this->data['getConcerts_previous'] = $getConcerts_previous; $this->render_layout('concerts/index', $this->data); }
Required Model Setup
Make sure you have a Festival_model with the corresponding method (mirroring your Hall_model):
// application/models/Festival_model.php public function getFestivalbyID($id) { return $this->db->get_where('Festivals', ['fID' => $id])->row(); }
Optional: Unified Venue Field
If you prefer a single field name instead of separate fFestival_ID and hHall_ID, you can simplify the loop to use a consistent venue_id:
foreach($getConcerts_previous as $concert) { $venueId = 'No data'; if ($concert->cPlaceType == 1) { $festivalData = $this->festival_model->getFestivalbyID($concert->cPlaceID); $venueId = $festivalData ? $festivalData->fID : $venueId; } elseif ($concert->cPlaceType == 2) { $hallData = $this->hall_model->getHallbyID($concert->cPlaceID); $venueId = $hallData ? $hallData->hID : $venueId; } $concert->venue_id = $venueId; }
Expected Result
For a concert with cPlaceType = 2, your var_dump will now show:
public 'cID' => string '45' (length=2) public 'cBand_ID' => string '8' (length=1) public 'cDate' => string '2018-06-22' (length=10) public 'hHall_ID' => string '1' (length=1)
内容的提问来源于stack exchange,提问作者TiboK
相关产品推荐
相关产品推荐

