Symfony findOneBy / findBy - doctrine

Has anyone face this strange issue with Symfony 3 (very last version)?
I have the following simple code:
$repository = $this->getDoctrine()
->getManager()
->getRepository('GeneralRegistrationBundle:Service');
$service = $repository->findOneBy(array('name' => 'Registration'),array('name' => 'ASC'));
$comment = $service->getComment();
$name = $service->getName();
return new Response('le service is '. $name . ', content is ' . $comment);
this code works.
I purge the cache and change findOneBy with findBy:
$service = $repository->findBy(array('name' => 'Registration'),array('name' => 'ASC'),1 ,0);
then I have the following error:
Error: Call to a member function getComment() on array
Is anybody have ideas or clues?
Thanks in advance.

findBy() returns an array of objects with the given conditions.
It returns an empty array if none is found. If there is only one row satisfying your condition then you can add a [0] at the last of your $service like this:
$service = $repository->findBy(array('name' => 'Registration'),array('name' => 'ASC'),1 ,0)[0];
if not, you should loop through the found array with foreach or some thing similar.

If you want and expect one result you can use findOneBy() function.
$service = $repository->findOneBy(array('name' => 'Registration'),array('name' => 'ASC'),1 ,0)[0];

Related

I've assigned Laravel Query Builder to a variable. It changes when being used

it's a WHY-question, not How-to one:)
I have assigned a Query Bulder to a variable $query:
$query = table::where(['id'=>1, 'this_version'=> 1]);
$versions['slug1'] = $query->select('tourist_id', 'tourist_version')->get()->toArray();
print_r($versions);
outputs array with 2(!) sub-arrays:
Array
(
[slug1] => Array
(
[0] => Array
(
[tourist_id] => 1
[tourist_version] => 1
)
[1] => Array
(
[tourist_id] => 2
[tourist_version] => 1
)
)
)
But if I add another line using $query between my $query declaration and it's usage in getting $version[2] array, my $version[2] output is shortened to a 1-dimensional array:
$query = previoustour2_tourist::where(['tour2_id'=>$tour->id, 'this_version'=> 1]);
// Added line:
$versions['slug0'] = $query->select('version_created')->first()->version_created;
//
$versions['slug1'] = $query->select('tourist_id', 'tourist_version')->get()->toArray();
print_r($versions);
outputs (note slug1 now has only 1 nested array):
Array
(
[slug0] => 2017-08-08 08:25:26
[slug1] => Array
(
[0] => Array
(
[tourist_id] => 1
[tourist_version] => 1
)
)
)
it seems like the like this line:
$versions['slug0'] = $query->select('version_created')->first()->version_created;
has added "first()" method to the original $query . Am I right and, if yes, why does it happen?
Well, this is because by default an object (in your case is the Query builder object) in PHP is passed by reference. You can read more about this here: PHP OOP References.
I quote from the above reference:
A PHP reference is an alias, which allows two different variables to
write to the same value.
When you pass the query builder object to the $query variable, you actually just pass the reference to this object and not the copy of it.
$query = previoustour2_tourist::where(['tour2_id'=>$tour->id, 'this_version'=> 1]);
So when you call the first() method on the second line, it actually modifies the query builder object.
$versions['slug0'] = $query->select('version_created')->first()->version_created;
Thus causing the upcoming query result to be limited to 1. In order to work around this issue, you can clone the query object like this:
$query = previoustour2_tourist::where(['tour2_id'=>$tour->id, 'this_version'=> 1]);
$versions['slug0'] = (clone $query)->select('version_created')->first()->version_created;
$versions['slug1'] = (clone $query)->select('tourist_id', 'tourist_version')->get()->toArray();
print_r($versions);
Hope this help!

how to print 2d array in laravel 5.4.12 by dd();?

please help me to solve this problem that how to die and dump 2D array in laravel and count array in an array.. i tried this but not working
$arr=collect($request->input('title['+$i+']'));
dd($arr->count());
also tried this code
$arr=collect($request->input('title[0]'));
dd($arr->count());
You do not say that you need to count them in your questions but here you go:
The aray:
$arrayname= array(
array('a', 'b', 'c'),
array('r', 't','y', 'u'),
);
The function
for ($i=0; $i < count($arrayname); $i++){
$singlearray[$i]= count($arrayname[$i]);
}
Result
array:2 [▼
0 => 3
1 => 4
]
dd($request->all()) will display contents of the array.
If you want to see the title, do this:
dd($request->title);
try to use:
echo count($arr);
dd($arr);
or
echo count($arr);
print_r($arr);
die;
$a = $request->all();
$flatArray = [];
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($a));
foreach($it as $v) {
$array[] = $v;
}
dd(count($flatArray));
Resource:
How to Flatten a Multidimensional Array?
i get it from the other site... Answer here
dd(count(request('title')[0]));
dd(count(request('title')['age']));

result_array() data in where clause in OR condition : Active records Codeigniter

result_array() for a query gives the following :
Array ( [0] => Array ( [id] => 1 ) [1] => Array ( [id] => 4 ) )
I want to use id=1 and id=4 in the where clause in the OR condition like the following :
$this->db->where_in('id',$query->result_array());
But the above causes error. Is there any direct way of doing the same?
You can simply use array_column
array_column($query->result_array(), 'id')
here is reference to it.
$result = $roleIdQuery->result_array();
$column = array_map(function($sub)
{
return $sub['id'];
}, $result);
I used this. Sadly.
because it has arrays within that array.
$ids=array();
$resultArray=$query->result_array();
foreach($resultArray as $result){
$ids[]=$result['id'];
}
$ids // this is what you need to pass now..
If you change your original query to use GROUP_CONCAT. Not an option in Active Record so would need to write your own SQL. something like
$query= $this->db->query('SELECT GROUP_CONCACT(id) AS ids FROM table WHERE condition=true');
Then you should be able to do
$this->db->where_in('id',$query->result_array()[0]['ids']);
Just noticed your on 5.3 so unfortunately that means this won't work you will have to do.
$result = $query->result_array();
Then pass in $result[0]['ids']

Laravel4 raw statement in the middle of complex where

I have a quite complex search method which handles the $input array from a controller, the thing is that I want to perform a custom SQL statement in the middle of it, for example:
$input['myField'] = array('condition' => 'rawStatement', value => 'AND WHERE LEFT(field,9) = 10`
and that would apply into my busy-conditions-method-builder
You can see the method at
http://pastebin.com/BNUKk2Xd
I'm trying to apply it on lines 52-54 but cant seem to get it working.
I know this is an old question but looking at your pastbin you have to chain your query like.
$query = User::join('user_personal','users.id','=','user_personal.user_id');
# Join user askings
$query = $query->leftJoin('user_askings','users.id','=','user_askings.user_id');
$query = ..........
$query = $query->orderBy('users.profile_score','DESC');
$query = $query->groupBy('users.id')->paginate(32);
return $query;

how to use 'like' instead of '=' in magento collection filter for custom module

i have managed to do this with addFieldToFilter default functionality like this:
$collection->addFieldToFilter(
array('first_name','last_name'),
array($post['firstName'],$post['lastName'])
);
this is working when i print sql (this is just part from the whole statement being printed):
((first_name = 'r') OR (last_name = 't'))
now i am trying to understand how to use 'like' instead of =.
need some help in understanding that.
your time and answers are highly appericiated thank you.
It's weird, but after some researching into your question the solution is quite simple - it's given in the comments in the Magento code:
In the comment for the method addAttributeToFilter() in Mage/Eav/Model/Entity/Collection/Abstract.php (which finally gets called) you can read:
/**
* Add attribute filter to collection
*
* If $attribute is an array will add OR condition with following format:
* array(
* array('attribute'=>'firstname', 'like'=>'test%'),
* array('attribute'=>'lastname', 'like'=>'test%'),
* )
*/
Wasn't quite clear to me what this was supposed to mean, but it's as simple: If you want to add an OR condition between the attributes in your statement, then you have to give your parameter for the addAttributeToFilter() method in this way, so in your case:
$collection->addFieldToFilter(
array(
array('attribute'=>'firstname', 'like'=>$post['firstName']),
array('attribute'=>'lastname', 'like'=>$post['lastName'])
));
You can follow this if you look inside the addAttributeToFilter() method:
if (is_array($attribute)) {
$sqlArr = array();
foreach ($attribute as $condition) {
$sqlArr[] = $this->_getAttributeConditionSql($condition['attribute'], $condition, $joinType);
}
$conditionSql = '('.implode(') OR (', $sqlArr).')';
For you googlers, the rigth way to to it is:
$collection->addFieldToFilter(
array('first_name','last_name'),
array(
array('like' => '%'.$post['firstName'].'%'),
array('like' => '%.'$post['lastName'].'%')
)
);
You should pass an array of fields and an array of conditions.
Generated SQL:
... WHERE ((first_name LIKE '%xxxx%') OR (last_name LIKE '%yyy%')) ...
addFieldToFilter( 'sku', array( "like"=>'abc123' ) )
Here you can read much more about Magento collections: http://alanstorm.com/magento_collections
For example, see section named "AND or OR, or is that OR and AND?" in this article.

Resources