I've following tables.
apartments
id name slug created modified
apartment_amenities
id name slug apartment_id created modified
apartment_activities
id name slug apartment_id created modified
In the view I wanted something like this.
no apartment_name amenities activities
1 shobha_comnplex party hall pamplets
swimming pool banners
play area boards
2 navami_comnplex party hall boards
swimming pool banners
club house pamplets
In the model I tried like this.
$this->db->select('apartments.id, apartments.slug, apartments.name, apartment_amenities.name as amenity_name, apartment_activities.name as activity_name');
$this->db->from($this->_table);
$this->db->join('apartment_amenities', 'apartment_amenities.apartment_id = apartments.id', 'left');
$this->db->join('apartment_activities', 'apartment_activities.apartment_id = apartments.id', 'left');
return $this->db->get();
But I'm getting only single amenity and activity even the apartment has many amenities and activities. The result is as follows.
Array
(
[0] =>
(
[id] => 1
[slug] => shobha_complex
[name] => shobha complex
[amenity_name] => party hall
[activity_name] => pamplets
),
[1] =>
(
[id] => 1
[slug] => navami_complex
[name] => navami complex
[amenity_name] => party hall
[activity_name] => boards
)
)
I want the result something like as follows.
Array
(
[0] =>
(
[id] => 1
[slug] => shobha_complex
[name] => shobha complex
[amenities] => Array(
[0] =>
(
[name] => party hall
),
[1] =>
(
[name] => swimming pool
),
[2] =>
(
[name] => play area
)
),
[activities] => Array(
[0] =>
(
[name] => pamplets
),
[1] =>
(
[name] => banners
),
[2] =>
(
[name] => boards
)
)
),
[1] =>
(
[id] => 1
[slug] => navami_complex
[name] => Navami complex
[amenities] => Array(
[0] =>
(
[name] => party hall
),
[1] =>
(
[name] => swimming pool
),
[2] =>
(
[name] => club house
)
),
[activities] => Array(
[0] =>
(
[name] => boards
),
[1] =>
(
[name] => banners
),
[2] =>
(
[name] => pamplets
)
)
),
)
Please suggest me how would I get the solution. The work would be more appreciated.
You can use group concat on your select and use as separator | so you will get only two row and on your view split the column with the separator
$this->db->select("GROUP_CONCAT(partment_amenities.name SEPARATOR '|') as amenity_name, ...... ", FALSE);
Second parameter FALSE for not to protect identifier
See the link for more about group concate:
https://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat
Remove the $this->db->group_by method call.
This would only return one result for each apartment. If you remove this, you should get all the amenities you want etc.
The only problem would be that you get results like this
no apartment_name amenities activities
1 shobha_comnplex party hall pamplets
1 shobha_comnplex swimming pool banners
1 shobha_comnplex play area boards
2 navami_comnplex party hall boards
2 navami_comnplex swimming pool banners
2 navami_comnplex club house pamplets
To setup a proper array, in the format your looking for i would advise having a few models in place.
Lets setup a scenerio
Controller:
$apartments = $this->apartment_model->getApartments(); // Get All Apartments
foreach($apartments as &$apartment)
{
$apartment->amenities = $this->apartment_model->getAmenities($apartment->id);
$apartment->activities= $this->apartment_model->getActivities($apartment->id);
// Add / Modify any addition properties
}
// Do something with the $apartments array
Model:
class Apartment_model extends model
{
function getApartments()
{
$this->db->select('id, slug, name');
$this->db->from('apartments');
$query = $this->db->get();
return $query->result();
}
function getAmenities($apartment_id)
{
$this->db->select('name');
$this->db->from('apartment_amenities');
$this->db->where('id', $apartment_id);
$query = $this->db->get();
return $query->result();
}
function getActivities($apartment_id)
{
$this->db->select('name');
$this->db->from('apartment_activities');
$this->db->where('id', $apartment_id);
$query = $this->db->get();
return $query->result();
}
}
Of course keep in mind this doesnt load the view yet or move your data anywhere past the controller, but it will at least setup the array.
I hope this helps get you started.
Related
I am trying to create a unit test for my application and wish to test that relationships exist. For my scenario, I have a model "Service" which has a "company_id" field for a belongsTo relationship.
I would like to use a factory in my test to create 10 "Services". Each service should have its own unique "Company"
I am getting closer all the time and my latest attempt was this
Here is the relationship in my Service model
/**
* Get the company a specified service belongs to
*
* #return BelongsTo
*/
public function company(): BelongsTo
{
return $this->belongsTo(Company::class);
}
And here is the code in my unit test. To physically see what is happening, I am outputting the results to the console.
Service::factory()
->count(10)
->create([
'company_id' => Company::factory()->create(),
]);
print_r((Company::all())->toArray());
print_r((Service::with(['company'])->get())->toArray());
The results are interesting.
I am correctly getting 10 services with a company_id populated.
All services have a company_id, but it is the same for each service
There is only one 'company' created
Although a 'company' has been created, the "company" relationship of the service is null
COMPANY
Array
(
[0] => Array
(
[id] => E39069C262B289573BA59BE5DA3DA182
[name] => Bartoletti, Boehm and Cronin
[account_number] => 013
[phone_number] => (864) 363-8603
[created_at] => 2022-11-22T10:22:12.000000Z
[updated_at] => 2022-11-22T10:22:12.000000Z
[deleted_at] =>
)
)
SERVICES
Array
(
[0] => Array
(
[id] => 92D9C3EEC3F550BBE627B0C7295E948E
[name] => Aut debitis quam excepturi dolor.
[company_id] => E39069C262B289573BA59BE5DA3DA182
[created_at] => 2022-11-22T10:22:12.000000Z
[updated_at] => 2022-11-22T10:22:12.000000Z
[deleted_at] =>
[company] =>
)
[1] => Array
(
[id] => B358067875A3AED5F2590321EE7040E3
[name] => Labore quia quia doloribus fuga adipisci.
[company_id] => E39069C262B289573BA59BE5DA3DA182
[created_at] => 2022-11-22T10:22:12.000000Z
[updated_at] => 2022-11-22T10:22:12.000000Z
[deleted_at] =>
[company] =>
)
... repeated 10 times
)
How can I use a factory to create 10 services, each with their own company?
For belongsTo relationship you can do:
Service::factory()
->count(10)
->for(Company::factory())
->create();
If you need different parent every time:
Service::factory()
->count(10)
->hasParent(Company::factory())
->create();
I'm trying to convert to Model binding on a Model built on customer orders. My route:
Route::model('order', 'App\Models\Order');
Route::resource('orders', 'OrderController');
This allows me to pull up an Order to edit through my controller (also grabbing statuses to populate a table and passing the logged in user):
public function index(Order $order)
{
$orders = $order->get();
return view('orders.index', compact('orders'));
}
My orders.index will display $order->id properly but when I try to loop through the Actions, which is connected by a hasMany relationship, nothing shows. Or I try to show $order->user->firstname which belongs to User by user_id.
#foreach( $order->actions as $action )
{{ $action->type->type }}
#endforeach
From my Action model:
public function order()
{
return $this->belongsTo('\App\Models\Order', 'order_id');
}
From my Order model:
public function actions()
{
return $this->hasMany('\App\Models\Action', 'order_id');
}
Here's an excerpt from a dump of the Order:
`Illuminate\Database\Eloquent\Collection Object
(
[items:protected] => Array
(
[0] => App\Models\Order Object
(
[table:protected] => orders
[timestamps] => 1
[dates:protected] => Array
(
[0] => deleted_at
)
[connection:protected] =>
[primaryKey:protected] => id
[perPage:protected] => 15
[incrementing] => 1
[attributes:protected] => Array
(
[id] => 1
[created_at] => 2015-03-16 23:42:45
[updated_at] => 2015-03-19 04:37:53
[deleted_at] =>
[user_id] => 16
[status_id] => 5
[address_id] => 5
[datetime_pickup_actual] =>
[datetime_delivery_actual] =>
[datetime_pickup_requested] => 2015-03-20 17:00:00
[datetime_delivery_requested] => 2015-03-21 17:00:00
[hold] => 0
[weight] => 20
)
[original:protected] => Array
(
[id] => 1
[created_at] => 2015-03-16 23:42:45
[updated_at] => 2015-03-19 04:37:53
[deleted_at] =>
[user_id] => 16
[status_id] => 5
[address_id] => 5
[datetime_pickup_actual] =>
[datetime_delivery_actual] =>
[datetime_pickup_requested] => 2015-03-20 17:00:00
[datetime_delivery_requested] => 2015-03-21 17:00:00
[hold] => 0
[weight] => 20
)
[relations:protected] => Array
(
)
[hidden:protected] => Array
(
)
[visible:protected] => Array
(
)
[appends:protected] => Array
(
)
[fillable:protected] => Array
(
)
[guarded:protected] => Array
(
[0] => *
)
[casts:protected] => Array
(
)
[touches:protected] => Array
(
)
[observables:protected] => Array
(
)
[with:protected] => Array
(
)
[morphClass:protected] =>
[exists] => 1
[forceDeleting:protected] =>
)`
As you compact orders in your controller you should use orders in your Blade template:
#foreach( $orders->actions as $action )
{{ $action->type->type }}
#endforeach
You should be also aware that Order in your index method in controller have nothing in common with Route Model Binding. For index it won't be used at all.
For other methods (show/edit/delete) it won't work because you make a binding with wrong name. It should be:
Route::model('orders', 'App\Models\Order');
and not
Route::model('order', 'App\Models\Order');
Model name (MoneyEntry)
Changed from
Route::resource('moneyentries', 'MoneyEntryController');
to
Route::resource('moneyEntries', 'MoneyEntryController');
Did a trick.
I have three models with the following relations
MODEL-1: RecoringSchedule
protected $recording_schedule = 'recording_schedules';
// relationship with processes
public function processes()
{
return $this->belongsToMany('Process', 'recording_uploads', 'recording_schedule_id', 'process_id');
}
MODEL-2: Process
protected $table = 'processes';
// relationship with recordings
public function recordings()
{
return $this->belongsToMany('RecordingSchedule', 'recording_uploads');
}
MODEL-3: RecordingUpload
protected $table = 'recording_uploads';
Here model3 is the pivot table which contains id, recording_schedule_id, process_id, created_at, updated_at
I have a query,
$recordings = RecordingSchedule::with('processes')->orderBy('recording_date_time', 'desc')->paginate(50)->toArray()
The above query is return all the recordings with process.
Now how can I apply filter by process_id which is in pivot table?
like where process_id = 3
I have tried Kousha answer
It is displaying
[id] => 35
[dialin_number] => 9908154124
[operator_extension] => 121
[recording_id] => 08631a03109
[max_duration] => 10
[recording_date_time] => 2014-07-31 13:06:00
[status] => ADDED
[created_by] => 32
[created_at] => 2014-07-31 12:06:48
[updated_at] => 2014-07-31 12:14:04
[processes] => Array
(
[0] => Array
(
[id] => 3
[name] => basic
[created_at] => 2014-07-10 12:22:06
[updated_at] => 2014-07-16 14:06:35
[pivot] => Array
(
[recording_schedule_id] => 35
[process_id] => 3
)
)
)
and also other recordings as below
[id] => 39
[dialin_number] => 939938333
[operator_extension] => 141
[recording_id] => 123456#
[max_duration] => 30
[recording_date_time] => 2014-07-31 12:19:00
[status] => ADDED
[created_by] => 32
[created_at] => 2014-07-31 13:20:16
[updated_at] => 2014-07-31 13:20:34
[processes] => Array
(
)
)
In the second array recording with empty processes are displaying. Actually that recording belongs to process id 6. I don't want other recordings with other process id.
Thanks in advance
You don't apply the filter on the pivot, but on the table processes:
$process_id = 3;
$recordings = RecodingsSchedule::with([
'processes' => function($query) use ($process_id)
{
$query->whereId($process_id);
}
])->orderBy('recording_date_time', 'desc')->paginate(50)->toArray();
I have an object called 'events', that's created via $data['events'] = function (the function pulls information out of an events table and others using active record).
The events object looks like:
Array
(
[0] => stdClass Object
(
[id] => 2
[course_name] => Course 3
[course_description] => Course
[course_price] => 995
[supplier_name] => Supplier 3
[location_country_code] => GB
[location_country] => United Kingdom
[location_city] => London
[venue_name] => Venue 2
[venue_address] => 2 Street
[venue_postcode] => EC2M 7PQ
[venue_city] => London
[venue_county] =>
[venue_country] => United Kingdom
[venue_locality] =>
[event_type] => Materials Only
[event_status] => Confirmed
[course_id] => 2
[event_duration] => 3
[event_start_date] => 2013-09-12
[event_date_added] => 2013-02-26 14:36:06
[event_status_id] => 2
[event_type_id] => 4
[tutor_id] => 0
[tutor_confirmed] => 0
[event_featured] => 0
[event_push] => 0
[event_active] => 0
[invigilator_id] => 0
[event_discount] =>
[event_max_delegates] => 16
[location_id] => 1
[venue_id] => 1
[supplier_id] => 2
)
[1] => stdClass Object
(
[id] => 1
[course_name] => Course Name
[course_description] => Course Description
[course_price] => 995
[supplier_name] => Supplier 1
[location_country_code] => GB
[location_country] => United Kingdom
[location_city] => London
[venue_name] => Venue Name
[venue_address] => Street
[venue_postcode] => EC2M 7PQ
[venue_city] => London
[venue_county] =>
[venue_country] => United Kingdom
[venue_locality] =>
[event_type] => Private Venue
[event_status] => Provisional
[course_id] => 1
[event_duration] => 3
[event_start_date] => 2013-11-13
[event_date_added] => 2013-02-26 09:56:17
[event_status_id] => 1
[event_type_id] => 3
[tutor_id] => 0
[tutor_confirmed] => 0
[event_featured] => 0
[event_push] => 0
[event_active] => 0
[invigilator_id] => 0
[event_discount] => 395
[event_max_delegates] => 16
[location_id] => 1
[venue_id] => 1
[supplier_id] => 1
)
)
I'd like to add a nested object under the key 'delegates' for each row using ActiveRecord, that pulls through the delegates attached to the event using a bridge table 'events_delegates_bridge' by comparing the 'event_id' and 'delegate_id columns in that table.
Essentially so that the object looks like so:
Array
(
[0] => stdClass Object
(
[id] => 2
[course_name] => Course 3
[delegates] => Array
(
[0] => stdClass Object
(
[id] => 1
[name] => Joe Bloggs
)
[1] => stdClass Object
(
[id] => 2
[name] => Joe Smith
)
[3] => stdClass Object
(
[id] => 3
[name] => Jane Doe
)
)
[course_description] => Course
[course_price] => 995
[supplier_name] => Supplier 3
[location_country_code] => GB
[location_country] => United Kingdom
[location_city] => London
[venue_name] => Venue 2
[venue_address] => 2 Street
[venue_postcode] => EC2M 7PQ
[venue_city] => London
[venue_county] =>
[venue_country] => United Kingdom
[venue_locality] =>
[event_type] => Materials Only
[event_status] => Confirmed
[course_id] => 2
[event_duration] => 3
[event_start_date] => 2013-09-12
[event_date_added] => 2013-02-26 14:36:06
[event_status_id] => 2
[event_type_id] => 4
[tutor_id] => 0
[tutor_confirmed] => 0
[event_featured] => 0
[event_push] => 0
[event_active] => 0
[invigilator_id] => 0
[event_discount] =>
[event_max_delegates] => 16
[location_id] => 1
[venue_id] => 1
[supplier_id] => 2
)
)
Any ideas how best to achieve this? Thanks.
Event Model
class Event_Model extends CI_Model {
public function get_events() {
$this->db->select( '*' );
$this->db->from( 'courses' );
$this->db->from( 'suppliers' );
$this->db->from( 'locations' );
$this->db->from( 'venues' );
$this->db->from( 'event_type' );
$this->db->from( 'event_status' );
$this->db->join( 'events', 'events.course_id = courses.id AND events.supplier_id = suppliers.id AND events.location_id = locations.id AND events.venue_id = venues.id AND events.event_type_id = event_type.id AND events.event_status_id = event_status.id', 'inner' );
$this->db->order_by( 'events.event_start_date', 'asc' );
$query = $this->db->get();
return $query->result();
}
}
Dashboard Controller
$data['events'] = $this->event_model->get_events();
Delegates Model
I've created this to get the delegate data. Do you think it can be used to add the correct delegates to the events object?
class Delegate_Model extends CI_Model {
public function get_delegates() {
$this->db->select( '*' );
$this->db->from( 'delegates' );
$this->db->from( 'events_delegates_bridge' );
$this->join( 'delegates', 'delegates.id = events_delegates_bridge.delegate_id', 'inner' );
$query = $this->db->get();
return $query->result();
}
}
Just tested this and it shows a blank page.
You're best off doing it with 2 separate queries.
$events = array();
$result = $this->db->query('SELECT * FROM events WHERE ...');
foreach($result->result_array() as $event) {
$events[$event['id']] = $event;
}
$result = $this->db->query('
SELECT * FROM events_delegates_bridge
JOIN delegates ON (delegate_id = delegates.id)
WHERE ...
');
foreach($result->result_array() as $delegate) {
if (!empty($events[$delegate['event_id']])) {
$events[$delegate['event_id']]['delegates'][] = $delegate
}
}
This bit of code just queries the events and puts them in an array indexed by the event id.
Then, a separate query runs to pull up the delegates, and attaches them to the appropriate event.
use $name=$variable->result_array();var_dump($name); I think This work
how do i pass a multi diminutional array to a view?
controller code
public function index(){
data['navs'] = array(
'name' => array('one', 'two', 'three'),
'link' => array('one', 'two', 'three'));
$this->load->view('adminView', $data);}
view code
<?php if ($navs) {
foreach ($navs as $nav) {
echo('<li>' . $nav->name . '</li>');
}
}?>
First of all you need to build the array, the right way. It should be something like:
$data['navs'] = array( array( 'name' => 'one',
'link' => 'linkone'),
array( 'name' => 'two',
'link' => 'linktwo')
);
$this->load->view('adminView', $data);
Then in your view:
foreach($navs as $n){
echo "<li><a href='{$n['link']}'>{$n['name']}</a></li>";
}
Once in the view, refer to your data as array elelements, not object properties (you are passing the array of arrays, not array of objects). Based on your controller, your view code should look like that:
foreach ($navs as $nav) {
echo('<li>' . $nav['name'] . '</li>');
}
However, that won't output the right result because your $nav['link'] and $nav['name'] are two arrays. You'd need to call any of their elements or change controller accordingly.
how to fetch dynamic array value by using controller of codeigniter in php
Array
(
[id] => 2
[name] => Wellness & Spa
[isSelected] => true
[subModules] => Array
(
[0] => Array
(
[id] => 1
[name] => Spa1
[isSelected] => true
[0] => object:81
)
[1] => Array
(
[id] => 2
[name] => Spa2
[isSelected] => true
[0] => object:82
)
[2] => Array
(
[id] => 3
[name] => Wellness
[isSelected] => true
[0] => object:83
)
)
)