Symfony2: Querying for object with 2 other objects as parameters - database

What is the best way to do the following: I have a gameobject entity which has properties game and user. Now my method gets the game id and the user id and i want to look for the gameobject with game = object of game id and user = object of user id.
I have tried the following:
$game = $this->getDoctrine()->getRepository("xxx:Game")->find($game_id);
$user = $this->getDoctrine()->getRepository("xxx:User")->find($user_id);
$gameobject_query = $em->getRepository('xxx:Gameobject')->createQueryBuilder('g')
->where('g.game = :game AND g.user = :user')
->setParameters(array(
'game' => $game,
'user' => $user
))
->getQuery();
$gameobject = $gameobject_query->getResult();
Your advices would be appriciated :)

I think that something like the following should work:
$repository = this->getDoctrine()->getRepository('xxx:GameObject');
$queryBuilder = $repository->createQueryBuilder('go')
->innerJoin('go.game', 'g')
->innerJoin('go.user', 'u')
->where('g.id = :gameId')
->andWhere('u.id = :userId')
->setParameter('gameId', $gameId)
->setParameter('userId', $userId);
$gameObjects = $queryBuilder->getQuery()
->execute();
Alternatively, the following may also work and be more efficient: It should do the same but without needing to join to the other entities:
$repository = this->getDoctrine()->getRepository('xxx:GameObject');
$queryBuilder = $repository->createQueryBuilder('go')
->where('IDENTIY(go.game) = :gameId')
->andWhere('IDENTITY(go.user) = :userId')
->setParameter('gameId', $gameId)
->setParameter('userId', $userId);
$gameObjects = $queryBuilder->getQuery()
->execute();

Why didn't you use the findOneBy method of your Gameobject repo ?
$game = $this->getDoctrine()->getRepository("xxx:Game")->find($game_id);
$user = $this->getDoctrine()->getRepository("xxx:User")->find($user_id);
$gameobject = $em->getRepository('xxx:Gameobject')->findOneBy(array(
'game' => $game,
'user' => $user
));

Related

node_load_multiple() can it go through the array?

I'm trying to do this to get the "floor" value of my node :
$type = "desk";
$floor = '2';
$nodes = node_load_multiple(array(), array('field_floor["und"][0]["value"]' => $floor, 'type' => $type));
I can get all my desk if I'm just doing $nodes = node_load_multiple(array(), array('type' => $type)); and I can find a deck with for exemple the title, but is it possible to go through the arrays to get the 'value' and check it in the query ?
Thank you for your answers.
To get value of a field you have multiple methods :
Field get item:
$nid = 2;
$node = node_load($nid);
$floor = field_get_items($node , 'node', 'field_floor');
$floor = reset($floor); // or loop on it, here take first value if multiple
echo $floor['value'];
https://api.drupal.org/api/drupal/modules%21field%21field.module/function/field_get_items/7.x
Entity metadata wrapper:
$nid = 2;
$node = node_load($nid);
$wrapper = entity_metadata_wrapper('node', $node);
$floor = $wrapper->field_floor->value();
echo $floor;
https://www.drupal.org/docs/7/api/entity-api/entity-metadata-wrappers
Direct way :
global $language; // take current language
$nid = 2;
$node = node_load($nid);
echo $node->field_floor[$language->language][0]['value'];

Laravel 5 form request

When I handle a CREATE post form, i'll do :
public function handlecreer(Requests\CreerUtilisateurRequest $request)
{
// handle create form
// all fields in one line... YEAH !!!
$user = new User($request->except('password','role'));
$user->password = bcrypt(Request::input('password'));
$user->save();
....}
But if I have an UPDATE post form I'll do :
public function handleUpdate(Requests\UpdateUtilisateurRequest $request)
{
// handle update form
$user = User::findOrFail(Request::input('id'));// find
// one line by field... BOH !!!
$user->name = Request::input('name');
$user->email = Request::input('email');
$user->password = bcrypt(Request::input('password'));
$user->telephone= Request::input('telephone');
$user->fonction = Request::input('fonction');
$user->divers = Request::input('divers');
$user->save();
....}
Is there a simplest way of processing the update post form ?
Thanks,
Paguemaou
All mass assignable attributes (the one in $fillable) can be set using fill():
$user = User::findOrFail(Request::input('id'));
$user->fill($request->except('password', 'role'));
$user->password = bcrypt(Request::input('password'));
$user->save();

Cakephp pagination for a custom function

I have a function in my model EmployeePersonal.php named get_employee_details which accepts some parameter and return the employees details. This function is used my many controllers and I prefer not to change this function.
Now I have a function view in my EmployeePersonalsController.php which outputs approx 4000 results. eg
$res = $this->EmployeePersonal->get_employee_details(
$office_id = $office_id,
$epf_no = $epf_no,
$employee_personal_id = $employee_personal_id,
$status = $status,
$permanent_district_id = $permanent_district_id,
$present_district_id = $present_district_id,
$department_id = $department_id,
$designation_id = $designation_id,
$category_id = $category_id,
$gender_type = $gender_type,
$offset = $offset,
$size = $size
);
I need to put a pagination in my view function , is there any way how can I put the $paginate here ?

How do you filter Joomla 3 articles by article id

I'm trying to create a Joomla module that displays articles based on categories and tags.
I've taken code for selecting tagged articles from https://github.com/lasinducharith/joomla-tags-selected) and introduced it into a copy of mod_articles_news:
public static function getList(&$params)
{
$app = JFactory::getApplication();
$db = JFactory::getDbo();
// Code base on https://github.com/lasinducharith/joomla-tags-selected to fetch ids of tagged articles
$tagsHelper = new JHelperTags;
$tagIds = $params->get('tagid', array());
$tagIds = implode(',', $tagIds);
echo '<pre>search for tags[' . $tagIds . ']';
$query=$tagsHelper->getTagItemsQuery($tagIds, $typesr = null, $includeChildren = false, $orderByOption = 'c.core_title', $orderDir = 'ASC',$anyOrAll = true, $languageFilter = 'all', $stateFilter = '0,1');
$db->setQuery($query, 0, $maximum);
$results = $db->loadObjectList();
$article_ids=array();
foreach ($results as $result){
$article_ids[]=$result->content_item_id;
}
echo ' yields articles[' . implode(',', $article_ids ) . ']</pre>';
// Get an instance of the generic articles model
$model = JModelLegacy::getInstance('Articles', 'ContentModel', array('ignore_request' => true));
// Set application parameters in model
$appParams = JFactory::getApplication()->getParams();
$model->setState('params', $appParams);
// Set the filters based on the module params
$model->setState('list.start', 0);
$model->setState('list.limit', (int) $params->get('count', 15));
$model->setState('filter.published', 1);
$model->setState('list.select', 'a.fulltext, a.id, a.title, a.alias, a.introtext, a.state, a.catid, a.created, a.created_by, a.created_by_alias,' .
' a.modified, a.modified_by, a.publish_up, a.publish_down, a.images, a.urls, a.attribs, a.metadata, a.metakey, a.metadesc, a.access,' .
' a.hits, a.featured' );
// Access filter
$access = !JComponentHelper::getParams('com_content')->get('show_noauth');
$authorised = JAccess::getAuthorisedViewLevels(JFactory::getUser()->get('id'));
$model->setState('filter.access', $access);
// Category filter
$model->setState('filter.category_id', $params->get('catid', array()));
// Article filter
$model->setState('filter.id', $article_ids);
// Filter by language
$model->setState('filter.language', $app->getLanguageFilter());
// Set ordering
$ordering = $params->get('ordering', 'a.publish_up');
$model->setState('list.ordering', $ordering);
if (trim($ordering) == 'rand()')
{
$model->setState('list.direction', '');
}
else
{
$direction = $params->get('direction', 1) ? 'DESC' : 'ASC';
$model->setState('list.direction', $direction);
}
// Retrieve Content
$items = $model->getItems();
$newitems=array();
foreach ($items as &$item)
{
echo '<pre>fetched article[' . $item->id .'] which is ';
if ( !in_array($item->id, $article_ids )){
echo 'not tagged';
} else{
echo 'tagged';
}
echo '</pre>';
...
}
return $newitems;
}
The debug statements give me:
search for tags[2] yields articles[40,44,45]
fetched article[45] which is tagged
fetched article[44] which is tagged
fetched article[43] which is not tagged
fetched article[42] which is not tagged
fetched article[41] which is not tagged
fetched article[40] which is tagged
fetched article[39] which is not tagged
fetched article[38] which is not tagged
So the articles have not been filtered by id. I'd be very grateful for any advice.
Thanks
Found the problem, the filter should be article_id:
// Article filter
$model->setState('filter.article_id', $article_ids);
Now it selects articles based on tags and categories

Using read() in cakephp to retrieve row with array of data

I want to know if it is possible to retrieve a row from the database using something similar to the following:
if (!empty($this->params['form'])) {
$place = array();
$place['city'] = $this->params['form']['city'];
$place['area'] = $this->params['form']['state'];
$place['country'] = $this->params['form']['country'];
$place['iso'] = $this->params['form']['iso'];
$this->Place->set($place);
$place_found = $this->Place->read();
}
Is there some way I can preset the data in the Place model using the array and then use Place read. I'm looking for something simple like the usual:
$this->Place->id = 7;
$place_found = $this->Place->Read();
I have also tried doing this:
$this->Place->city = blah;
$this->Place->area = foo; etc....
$place_found = $this->Place->read();
However, that also does not work.
Haven't you ever used find()?! read() only fetches a row with the ID passed.
$place_found = $this->Place->find('first', array(
'conditions' => array(
'Place.city' => $city,
'Place.area' => $area
// etc
)
));
If you need to build the conditions manually you can create a conditions array to pass like so:
$placeConditions = array();
$placeConditions['city'] = $city;
if($area) {
$placeConditions['area'] = $area;
}
$places = $this->Place->find('first', array('conditions' => $placeConditions));
I suggest you read the page I linked, you will soon find out there is never a reason to use the read() method.
In model you could do:
$this->id = 3; //place id
$this->Place->read();
Hope it helps
I think this approach is what you're looking for(with your code):
if (!empty($this->params['form'])) {
$place = array();
$place['city'] = $this->params['form']['city'];
$place['area'] = $this->params['form']['state'];
$place['country'] = $this->params['form']['country'];
$place['iso'] = $this->params['form']['iso'];
//$this->Place->set($place); //don't need it here I think
$place_found = $this->Place->find('all',array('conditions'=>$place));
}
You'll have to use "find()", not "read()", but - it's almost as simple as your example code and should work. (also, there's a shortcut for the array_push() I believe, but - I like to use this for readability - personal preference):
if (!empty($this->params['form'])) {
$conditions = array();
array_push($conditions, array('Place.city' => $this->params['form']['city']);
array_push($conditions, array('Place.state' => $this->params['form']['state']);
array_push($conditions, array('Place.country' => $this->params['form']['country']);
array_push($conditions, array('Place.iso' => $this->params['form']['iso']);
$this->Place->set($place);
$place_found = $this->Place->find('all', array('conditions'=>$conditions));
}

Resources