If I need to query more than 10,000 records and associate the fields of other tables, how can I be efficient?

$cardNoBegin = 1;
$cardNoEnd = 10000;
$where["number"] = array("between" , [$cardNoBegin , $cardNoEnd]);
$list = VipCardModel::where($where)->field("id,number,issue_uid,rank")->select();
foreach($list as &$value){
    // foreach
    $value["name"] = UserModel::where(array("id" => $value["issue_uid"]))->value("name");
}
May.14,2022

shmiyle has answered this question correctly. I'll optimize it on his basis to improve the efficiency a little bit

$where['number'] = array('between' , [$cardNoBegin , $cardNoEnd]);
$list = VipCardModel::where($where)->field('id,number,issue_uid,rank')->select();
$issueUidList = array_unique((array_column($list, 'issue_uid')));
unset($list);

//
$userList = UserModel::where(array('id' => array('in', $issueUidList)))->value('name');
$userInfoList=array_column($userList,'name','id');

foreach($list as $key => $value){
    $list[$key]['name'] = $userInfoList[$value['issue_uid']] ?? '';
}

this is definitely not advisable, and the query is executed in the loop.
you can try with

  

this is definitely not advisable, and the query is executed in the loop.
you can try with

Menu