PHP 및 PDO를 사용하여 매일 데이터베이스를 작동시킬 때 Pdostatement :: FetchObject 는 매우 편리한 방법으로 쿼리 결과를 객체로 직접 변환 할 수 있습니다. 그러나 기본적으로 기본적으로 만 생성되며 더 복잡성을 자동으로 처리하지 않습니다. 결과에 프로필 객체를 중첩하기 위해 사용자 객체와 같은 중첩 된 객체를 포함하려면 직접 처리해야합니다.
이 목표를 단계별로 달성하는 방법을 살펴 보겠습니다.
다음과 같은 두 개의 테이블이 있다고 가정합니다.
CREATE TABLE users (
id INT PRIMARY KEY,
name VARCHAR(100),
profile_id INT
);
CREATE TABLE profiles (
id INT PRIMARY KEY,
bio TEXT,
avatar_url VARCHAR(255)
);
프로필 객체를 중첩하는 동안 사용자 데이터를 쿼리하고 결과를 사용자 객체로 전환하려고합니다.
예를 들어, 나는 이와 유사한 구조를 얻고 싶습니다.
User {
id => 1,
name => 'Alice',
profile => Profile {
id => 2,
bio => 'Hello world!',
avatar_url => 'https://gitbox.net/uploads/avatar.jpg'
}
}
사용자 및 프로필을 위한 PHP 클래스를 만들어야합니다.
class Profile {
public int $id;
public string $bio;
public string $avatar_url;
}
class User {
public int $id;
public string $name;
public Profile $profile;
}
가입 쿼리를 사용하여 두 테이블에서 데이터를 한 번에 검색 할 수 있습니다.
$sql = "
SELECT
u.id AS user_id,
u.name AS user_name,
p.id AS profile_id,
p.bio AS profile_bio,
p.avatar_url AS profile_avatar_url
FROM users u
JOIN profiles p ON u.profile_id = p.id
";
$stmt = $pdo->query($sql);
FetchObject는 기본적으로 하나의 데이터 계층 만 맵핑하므로 중첩 된 객체를 직접 조립해야합니다. 당신은 이것을 할 수 있습니다 :
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$user = new User();
$user->id = (int) $row['user_id'];
$user->name = $row['user_name'];
$profile = new Profile();
$profile->id = (int) $row['profile_id'];
$profile->bio = $row['profile_bio'];
$profile->avatar_url = $row['profile_avatar_url'];
$user->profile = $profile;
// 지금 $user 둥지가 포함되어 있습니다 Profile 의 대상
var_dump($user);
}
종종이 문제를 처리 해야하는 경우 가제트 기능으로 캡슐화 할 수 있습니다.
function mapRowToUser(array $row): User {
$user = new User();
$user->id = (int) $row['user_id'];
$user->name = $row['user_name'];
$profile = new Profile();
$profile->id = (int) $row['profile_id'];
$profile->bio = $row['profile_bio'];
$profile->avatar_url = $row['profile_avatar_url'];
$user->profile = $profile;
return $user;
}
// 사용
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$user = mapRowToUser($row);
var_dump($user);
}
pdostatement :: FetchObject 자체는 중첩 된 객체를 직접 만들 수는 없지만 수동 할당 및 캡슐화를 통해 복잡한 데이터 구조 매핑을 구현하는 것이 매우 유연 할 수 있습니다. 이 방법은 단순한 배열 처리보다 더 안전하고 안전하며 현대적인 PHP 객체 지향 개발 습관과 일치합니다.
더 단순화하려면 ORM 도구 (예 : Eloquent, Doctrine)를 결합하여 이러한 매핑을 자동으로 처리하는 것을 고려할 수 있지만 가벼운 프로젝트의 경우이 수동 매핑 방법이 이미 충분합니다!