php - get limited numbers of data with yii2
Solution:
$departures = ArrayHelper::map( TourDeparture::find()->limit(5), 'id', 'tour_id' );
I wrote it like above. but ı got all the record
I'm surprised your code worked at all! You are passing the Query
class into the map
function. ArrayHelper::map
is expecting an array and needs the query to be executed using the ->all()
. ->limit(5)
just adds a new term to the SQL query.
$departures = ArrayHelper::map( TourDeparture::find()->limit(5)->all(), 'id', 'tour_id' );
Answer
Solution:
for retrieve the first 5 rows should be
TourDeparture::find()->orderBy("id")->limit(5)->all()
Answer
Solution:
The code you shared didn't do the limit(5). Anyway, I believe it is caused by the array map, you may try to simulate the changes as below
$q = TourDeparture::find()->select(['id', 'tour_id'])->limit(5)->asArray()->all();
\yii\helpers\VarDumper::dump($q, $depth = 10, $highlight = true);
For the above, records selected in array form, before array map.
After array map, from here you can compare the changes.
$departures = ArrayHelper::map(
$q,
'id',
'tour_id'
);
\yii\helpers\VarDumper::dump($departures, $depth = 10, $highlight = true);
Source