I just teach Symfony and Doctrine.
I don't know hot to fetch 1 row array instead of multirow array in Doctrine.
I using this:
$q = $this->createQuery('a')
->innerJoin('a.Translation t')
->andWhere('t.lang = ?', $language)
->andWhere('t.name LIKE ?', 'somename%');
return $q->execute(array(), Doctrine::HYDRATE_RECORD);
And then i get something like:
Array
(
[0] => Array
(
[id] => 1
[created_at] => 2012-03-19 17:40:52
[updated_at] => 2012-03-21 17:44:04
[created_by] => 1
[updated_by] => 1
[Translation] => Array
(
[en] => Array
(
[id] => 1
[name] => somename
[lang] => en
[slug] => somename
)
)
)
)
But i need
Array
(
[0] => Array
(
[id] => 1
[created_at] => 2012-03-19 17:40:52
[updated_at] => 2012-03-21 17:44:04
[created_by] => 1
[updated_by] => 1
[id] => 1
[name] => somename
[lang] => en
[slug] => somename
)
)
Some body knows how i can make it?
I use just
$q = $this->createQuery('a')
->select('a.id as id, t.name as name')
->leftJoin('a.Translation t')
->where('t.name LIKE ?', $name.'%')
->andWhere('t.lang = ?', $language);
Have you tried to explicit add a select with columns you need?
$q = $this->createQuery('a')
->select('a.id, a.created_at, a.updated_at, a.created_by, a.updated_by, t.id, t.name, t.lang, t.slug')
->innerJoin('a.Translation t')
->andWhere('t.lang = ?', $language)
->andWhere('t.name LIKE ?', 'somename%');
return $q->execute(array(), Doctrine::HYDRATE_ARRAY);
Using the WITH keyword?
$q = $this->createQuery('a')
->innerJoin('a.Translation t WITH t.lang = ?', $language)
->where('t.name LIKE ?', 'somename%');
return $q->execute(NULL, Doctrine::HYDRATE_ARRAY);
Related
I'm trying to get videos from my channel using search function. Response include only nextPageToken, but no prevPageToken. prevPageToken is null always, even if I'm listing other pages using nextPageToken. I use an access_token param from Google Oauth.
My request:
$searchResponse = $youtube->search->listSearch('snippet', array(
'forMine' => 'true',
'order' => 'date',
'pageToken' => $pageToken,
'type'=>'video',
'maxResults' => '10',
'q' => $searchQuery,
));
Result:
Google_Service_YouTube_SearchListResponse Object
(
[collection_key:protected] => items
[etag] => "XXX"
[eventId] =>
[itemsType:protected] => Google_Service_YouTube_SearchResult
[itemsDataType:protected] => array
[kind] => youtube#searchListResponse
[nextPageToken] => Cib3-ZrgSf____9uWHdEYVNIVnlOVQD_Af_-blh3RGFTSFZ5TlUAARAPIbmtEhE6-iWlOQAAAAC2H2UGSAFQAFoLCdIYcGeU2-YsEAJgyOjNygE=
[pageInfoType:protected] => Google_Service_YouTube_PageInfo
[pageInfoDataType:protected] =>
[prevPageToken] =>
[regionCode] =>
[tokenPaginationType:protected] => Google_Service_YouTube_TokenPagination
[tokenPaginationDataType:protected] =>
[visitorId] =>
[internal_gapi_mappings:protected] => Array
(
)
[modelData:protected] => Array
(
)
[processed:protected] => Array
(
)
[pageInfo] => Google_Service_YouTube_PageInfo Object
(
[resultsPerPage] => 5
[totalResults] => 55
[internal_gapi_mappings:protected] => Array
(
)
[modelData:protected] => Array
(
)
[processed:protected] => Array
(
)
)
Thank you for your ideas!
Petr
UPDATE
This problem is only if is set param forMine. But I need show only my videos...
I want to insert multiple row in single table using foreach.
<pre class='code'>Array
(
[instructor_id] => 76
[vehicle_id] => 2
[arr_bookings] => Array
(
[0] => Array
(
[0] => 07-10-2016
[1] => 1:10 PM
[2] => 2:02 PM
[3] => s
[4] => s
)
[1] => Array
(
[0] => 07-10-2016
[1] => 1:15 PM
[2] => 2:01 PM
[3] => a
[4] => a
)
)
)
my result is this in print_r($result). how can i insert using foreach? any ideas about this.
You would do something like.
$sql = "INSERT INTO table_name (column_1, column_2) VALUES";
Then loop through your array like,
$last_key = end(array_keys($array));
foreach ( $array as $key => $value ) {
// Don't forget to protect against SQL injection.
$sql .= "('$value[0]', '$value[1]')";
if ( $last_key === $key ) {
$sql .= ",";
}
}
After that you should have a sql statement that looks something like INSERT INTO table_name (column_1, column_2) VALUES ('Some Value', 'Another Value'), ('foo', 'bar').
I am getting array data from a function ReportsController::getStudentYearwiseAvgHeightsProvince() in the below format:
Array ( [0] => Array ( [name] => Baluchistan [data] => Array ( [0] => 0 [1] => 0 [2] => 0 [3] => 0 [4] => 0 [5] => 0 [6] => 0 ) ) [1] => Array ( [name] => KPK [data] => Array ( [0] => 56 [1] => 58 [2] => 58 [3] => 0 [4] => 0 [5] => 0 [6] => 60 ) ) [2] => Array ( [name] => Punjab [data] => Array ( [0] => 0 [1] => 0 [2] => 0 [3] => 78 [4] => 90 [5] => 90 [6] => 0 ) ) [3] => Array ( [name] => Sindh [data] => Array ( [0] => 0 [1] => 0 [2] => 0 [3] => 0 [4] => 0 [5] => 0 [6] => 0 ) ) )
ReportsController::getStudentYearwiseAvgHeightsProvince() function is:
public function getStudentYearwiseAvgHeightsProvince() {
$result = Yii::$app->db->createCommand ( '
SELECT temp.name AS name,
GROUP_CONCAT(IFNULL(temp.height,0) order by year) AS data
FROM ( SELECT years.year AS year, p.name AS NAME, FLOOR(AVG(sd.height)) AS height
FROM (
SELECT DISTINCT year FROM student_detail ORDER BY year
) years
cross join province p
left join student_detail sd on years.year = sd.year and sd.province_id = p.id
GROUP BY years.year, p.name
ORDER BY years.year )
AS temp
GROUP BY name; ' )->queryAll ();
$i = 0;
foreach ($result as $innerArray) {
$result[$i]['data'] = explode(",", $result[$i]['data']);
//$result[$i]['name'] = $innerArray['name'];
$i++;
}
//$result = array_map(function($var){ return (int) $var['data']; }, $result); // extraction from 2 level associative arry to 1-d associative array
print_r ( $result );
return $result;
}
and I am setting highcharts component as follows:
echo Highcharts::widget([
'scripts' => [
'modules/exporting',
'themes/grid-light',
],
'options' => [
'title' => ['text' => 'Student Province-wise Yearly Avg Heights'],
'plotOptions' => [
'column' => [
'depth' => 25
]
],
'xAxis' => [
'categories' => ReportsController::getDistinctCols("student_detail", "year")
],
'yAxis' => [
'min' => 0,
'title' => ['text' => 'Avg Height']
],
'series' =>
ReportsController::getStudentYearwiseAvgHeightsProvince()
]
]);
No graph is generated :(
I fixed the graph not showing issue by just converting the STRING ARRAY to INTEGER ARRAY which is returned by EXPLODE in my function getStudentYearwiseAvgHeightsProvince()
by editing the code inside FOREACH LOOP as:
foreach ($result as $innerArray) {
$result[$i]['data'] = explode(",", $result[$i]['data']);
$temp = array();
foreach ($result[$i]['data'] AS $index => $value)
$temp[$index] = (int)$value;
$result[$i]['data'] = $temp;
$i++;
}
I have this query but I can't seem to find how I set my WhereRestrictionOn as an OR. Now they function as AND but I want one OR the other.
var privateInfo = Session.QueryOver<ConContact>()
.JoinAlias(c => c.PrivateInfos, () => pi)
.WhereRestrictionOn(c => c.FirstName).IsLike(_selectedFirstLetter + "%")
.WhereRestrictionOn(c => c.LastName).IsLike(_selectedFirstLetter + "%") // todo: change to firstname OR lastname
.Where(c => c.Status == ContactStatus.Approved)
.Select(
Projections.Property("pi.Id").WithAlias(() => sri.Id),
Projections.Property("FirstName").WithAlias(() => sri.Name), //todo: get fullname here => Add concontact object in privateinfo
Projections.Property("pi.Address").WithAlias(() => sri.Address),
Projections.Constant("Contact").WithAlias(() => sri.Type)
)
.TransformUsing(Transformers.AliasToBean<SearchResultInfo>())
.List<SearchResultInfo>()
.ToList();
Any help is much appreciated thx!
SOLUTION:
var privateInfo = Session.QueryOver<ConContact>()
.JoinAlias(c => c.PrivateInfos, () => pi)
.Where(
Restrictions.Disjunction()
.Add(Restrictions.Like("FirstName", _selectedFirstLetter + "%"))
.Add(Restrictions.Like("LastName", _selectedFirstLetter + "%"))
)
.Where(c => c.Status == ContactStatus.Approved)
.Select(
Projections.Property("pi.Id").WithAlias(() => sri.Id),
Projections.Property("FirstName").WithAlias(() => sri.Name), //todo: get fullname here => Add concontact object in privateinfo
Projections.Property("pi.Address").WithAlias(() => sri.Address),
Projections.Constant(NewObjectType.Contact).WithAlias(() => sri.Type)
)
.TransformUsing(Transformers.AliasToBean<SearchResultInfo>())
.List<SearchResultInfo>()
.ToList();
The top level .Where() family (including WhereRestrictionOn) is always joined with AND. So we have to explicitly use something like:
Restrictions.Or(restriction1, restriction1)
Restrictions.Disjunction().Add(restriction1).Add(restriction2).Add(...
So, this could be our case:
.Where(
Restrictions.Disjunction()
.Add(Restrictions.On<ConContact>(c => c.FirstName)
.IsLike(_selectedFirstLetter, MatchMode.Start))
.Add(Restrictions.On<ConContact>(c => c.LastName)
.IsLike(_selectedFirstLetter, MatchMode.Start))
// more OR ...
//.Add(Restrictions.On<ConContact>(c => c.MiddleName)
// .IsLike(_selectedFirstLetter, MatchMode.Start))
)
As discussed here: 16.2. Simple Expressions, for simple stuff we can even use || (cited small example):
.Where(p => p.Name == "test name" && (p.Age > 21 || p.HasCar))
statuses = %w(sick healthy hungry)
query = User.scoped(:joins => 'left outer join pets on pets.user_id = users.id', :conditions => { 'pets.id' => nil, 'users.job_status' => stati })
Given the code above, is it possible to add an OR clause to the :conditions to say something like
where (pets.id is NULL AND users.status IN ('sick', 'healthy', 'hungry')) OR (users.gender = 'male')
You can do the following using the MetaWhere gem
statuses = %w(sick healthy hungry)
query = User.include(:pets).where(
('pets.id' => nil, 'users.job_status' => statuses) |
('users.gender' => 'male')
)
The | symbol is used for OR condition.
PS : The include directive uses LEFT OUTER JOIN so there is no need to hand code the JOIN.
You could use an SQL condition instead of a Hash condition:
query = User.scoped(
:joins => 'left outer join pets on pets.user_id = users.id',
:conditions => [
'(pets.id is null AND users.status IN (?)) OR (users.gender = ?)',
statuses, 'male'
]
)
Or:
query = User.scoped(
:joins => 'left outer join pets on pets.user_id = users.id',
:conditions => [
'(pets.id is null AND users.status IN (:statuses)) OR (users.gender = :gender)',
{ :status => statuses, :gender => 'male' }
]
)
The downside is that you have to avoid trying pets.is = NULL by hand.