Optional belongsTo relationship in cakephp - php

I have a simple Category model in my CakePHP application. I want to add sub-categories, and do this by simply adding a parent_id column.
The parent_id is a belongsTo relationship, that references back to the same Category model.
When I generate my admin scaffolds, a dropdown will shop up (correct!), but I'd like to include a NULL option in this dropdown (for top-level categories).
Is this possible? And if so, how..
(Note: not interested in Tree behaviour right now)

Sounds like you may be looking for the empty option:
<?php echo $form->input(
'field',
array( 'options' => array( 1, 2, 3, 4, 5),
'empty' => 'Select one'
); ?>
http://book.cakephp.org/view/201/options-empty

Related

Multiselect box keep database values as selected Laravel 5.8

I am using the multi-select box as follows, where I want to keep old values as selected in edit mode.
{!!Form::select('team_id[]',$teams , old('team_id[]') , array('class'=>'custom-select', 'id'=>'team_id', 'multiple'=>true)) !!}
Below is my controller code.
$teams = Teams::select('team_name', 'id as team_id')
->where('team_status_id', 1)
->pluck('team_name', 'team_id');
$teams->prepend('Select Teams', 0);
I have 2 tables. One is teams table, which contains the name of all teams. Other is team_applied table which contains team_id and survey_id. In add form, I want to display all team name in the multi-select box, and in edit mode, I want to show all team ids in team_applied table as selected along with other unselected team names.
Below is teams table:
Below is team_applied table:
Here is my select box which I need values as selected:
For showing multiple item selected at the time of edit, try something like this:
Form::select('size[]',['L' => 'Large', 'M' => 'Medium', 'S' => 'Small'], ['S', 'M'], ['multiple' => 'multiple', 'class' => 'form-control']);
// here ['S', 'M'] is the array that we have to show selected
Reference

Pulling data from another table while I have the index keys from my table

I have three Mysql tables:
Brands ( brand names , brand Ids)
cars ( car names,car ids, brand Ids)
statuss ( car Ids, each car status).
I am trying to pull the brand names from the brand table but I have the cars IDs. How can I do that see my code below.
Controller.ctp
$this->loadModel('car');
$cars = $this->car>find('all',array('limit' => 6, 'order' => array('car.id' => 'asc')));
$this->set('cars', $cars);
$this->loadModel('status');
$cars = $this->status>find('all',array('limit' => 6, 'order' => array('status.id' => 'asc')));
$this->set('statuss', $statuss);
View.ctp
App::import('Controller', 'cars');
$carsCont = new carsController;
App::import('Controller', 'brands');
$brandCont = new brandsController;
foreach($statuss as $status)
{
$car_info = $carsCont->get_car_info($status['status']['car_id']);
$car_name = $car_info['car_name'];
$car_id = $status['status']['car_id'];
$brand_list = $brandCont -> get_brand_name($status['car']['brand_id']); <---- this is not working
echo $brand_list['brand']['brand']; echo $car_name;
}
CakePHP controllers are not designed or meant to be instantiated directly like you are doing.
Rather, you should be making use of the associations that cakephp gives you.
Based on what you've said, you've got Statuses belongsTo Cars belongsTo Brands. Set those relations up in your model files (as documented in the book: http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html)
If you then use the containable behavior (http://book.cakephp.org/2.0/en/core-libraries/behaviors/containable.html) you'd be able to do something like (In your status controller)
$statuses = $this->Statuses->find('all', [
'contain' => ['Cars' => 'Brands']
]);
and you should have all the data that you need.
Edit: Based on your additions, change your cars query to
$cars = $this->car>find('all',array('limit' => 6, 'order' => array('car.id' => 'asc'), 'contain' => ['Brands']));
But, make sure Cars BelongsTo Brands, and you've attached the Containable behaviour.

MySQL result multiple arrays

i.e : i have 2 tables
Product ( id, name )
Photo ( id, name, photo_id )
And I need to get result in array like this:
array(
'id' => 1,
'name' => product,
'photos' => array(
array('id' => 1, 'name' => 'photo1')
array('id' => 2, 'name' => 'photo2')
)
}
Is it possible in PHP using clear SQL?
I know that is possible to get 2 arrays and connect it but I have many records and I dont want to wase time to quering.
You have to add a foreign_key in your photo table "product_id".
Then create a method getPhotos() in your Product class with will collect all photos for your product.
Is it possible in PHP using clear SQL?
Not in a single SQL call. With a single call, this is the closest you can get:
array(
'id' => 1,
'name' => product,
'photo_id' => 1,
'photo_name' => 'photo1')
),
array(
'id' => 1,
'name' => product,
'photo_id' => 2,
'photo_name' => 'photo2')
)
Your only choice for the format you want is to run queries separately or to combine them into the data structure you want.
As mentioned, this is not possible with SQL. SQL is based on the relational model which is a 1-Normal-Form data model. That means, the result relation is also flat (no nested relations in a relation).
However, there are good frameworks which generate intermediary models in your corresponding target language (e.g. Python, Java, ...) that circumvent the impression of a flat data model. Check for example Django.
https://docs.djangoproject.com/en/1.8/topics/db/models/
Moo

Some small issue in getting the associated model data in cakephp?

I have 2 models product and image. Product has an Has-many relationship with Image. I want to fetch both products and images records based on product id.So I have written the query like this
$this->Product->find('all',array('conditions'=>array('product_id'=>230));
I am getting all product table entries but not image tables records. I checked with var_dump(), then images table entries are coming like this
array('Images =>
array
0 =>
array
...
1 =>
array
... );
What might be the problem? Any help would be appreciated.
Thanks in advance
Pushpa
$this->Product->find('first', array(
'conditions' => array('Product.id' => 230),
'recursive' => 1 // ensures we are retrieving related models
)
);

CakePHP paginate conditions in derived fields

i would like to paginate a list of games, where the sport is a chosen sport.
the relatition is as followed:
Game BelongsTo Competition BelongsTo Team BelongsTo sport
What i would like to do is show all games where the teams sport_id = 1.
The following doesn't work:
$this->paginate = array('limit' => 30, 'page' => 1,
'conditions' => array('Competition.Team.sport_id' => '1'),
'contain' => array('Competition', 'Competition.Team',
'Gamefield', 'Changingroom', 'ChangingroomAway', 'Gametype'),
'order'=>array('game_date'=>'asc'),
);
Can anyone help me with this one?
I've found my solution:
var $paginate=array(
'Game'=>
array(
'joins'=>array(
array('table'=>'competitions',
'alias'=>'Competition2',
'type'=>'left',
'conditions'=>array('Game.competition_id=Competition2.competition_id')
),
array('table'=>'teams',
'alias'=>'Team2',
'type'=>'left',
'conditions'=>array('Competition2.team_id=Team2.team_id')
),
),
'order'=>array('game_date'=>'asc'),
'contains'=>array('Competition2'=>array('Team2'))
));
function index() {
$datum = date('Y-m-d H:m');
$this->Game->recursive = 0;
$scope=array('OR' => array(array('Team2.sport_id' => 2), array('Team2.sport_id' =>3)), 'Game.game_date >' => $datum);
// Configure::write('debug',2);
$this->set('games', $this->paginate(null,$scope));
}
Thanks to TehThreag for helping me
Containable doesn't create any joins unless the relation would have been joined anyways, despite using Containable.
This means that for habtm, if you want a join you have to do as Michael did and specify them.
Also, doing a couple of joins should be faster with logical indexes than doing a habtm with Containable anyways, as the results from a contain for the same data as above would require an in ( id1,id2,...id# ) condition and a number of queries from there to fetch the individual related records.
The joins solution gets the data back in one db query.

Categories