我不明白爲什麼不,但不知道你的關聯是如何相關的。 One-to-One
,One-to-Many
,或Many-to-Many
如果你正在嘗試從第三關聯深度級別記錄,如Account.profile
- >Profile.code
- >Code.xxx (not id)
你就需要使用DQL或或QueryBuilder的,以確定哪些個人資料和代碼分別爲加入賬戶或解決代碼實體提供給標準。
假設One-to-Many
其中一個帳戶有許多配置文件。您也可以選擇在實體內定義它,以便管理和減少對getProfiles()
的額外呼叫。
庫使用
use Doctrine\ORM\EntityRepository;
use Doctrine\Common\Collections\Criteria;
class AccountRepository extends EntityRepository {
/**
* @var string|Account $accountOrEmail
* @var string $code
* @return Profile|null
*/
public function getAccountProfileByEmailAndCode($accountOrEmail, $code)
{
try{
$account = ($accountOrEmail instanceof Account ? $accountOrEmail: $this->findOneBy(['email' => $accountOrEmail]));
if (!$account instanceof Account) {
throw new \InvalidArgumentException('Unknown Account Specified.');
}
$criteria = Criteria::create()->setMaxResult(1);
$expr = $criteria::expr();
$criteria->where($expr->eq('code', $code));
return $account->getProfiles()->matching($criteria)->first();
} catch(\Exception $e) {
return null;
}
}
}
$accountRepo = $em->getRepository('\Entities\Account');
$profile = $accountRepo->getAccountProfileByEmailAndCode('[email protected]', '12345');
實體使用
use Doctrine\Common\Collections\Criteria;
/**
* @ORM\Entity(repositoryClass="AccountRepository")
*/
class Account {
// ...
public function getProfiles(Criteria $criteria = null)
{
if ($criteria instanceof Criteria) {
return $this->profiles->matching($criteria);
}
return $this->profiles;
}
/**
* @var string $code
* @return null|Profile
*/
public function getProfileByCode($code)
{
$criteria = Criteria::create()->setMaxResult(1);
$expr = $criteria::expr();
$criteria->where($expr->eq('code', $code));
return $this->getProfiles($criteria)->first();
}
}
$account = $em->getRepository('\Entities\Account')->findOneBy(['email' => '[email protected]']);
$profile = $account->getProfileByCode('12345');
我不會深入兩層。我想通過直接關聯的屬性進行過濾。例如,'A'與'B'關聯。我想找到'A'的條目,其中'B.something ='some_value''。如果可能,我只想確保在數據庫中完成工作。另外,我並不是試圖將教義塑造成不是的東西;我只是想知道是否有一種方法可以實現這種「我的方式」,這種方式是內置於教義中的,我不知道。否則,我將使用DQL就好了,但如果可能的話,我寧願使用'Criteria'對象。 :-) – Andy0708
您無法使用Criterias搜索相關實體的屬性。您只能搜索實體本身的屬性。 –
好的,那就是我的想法 - 不幸的是。謝謝。 – Andy0708