Php 使用原则按特定列联接表
我试图通过检查两个关联表中的变量来获取一个表的单个记录 例如,我的桌子是Php 使用原则按特定列联接表,php,mysql,doctrine,symfony-1.4,left-join,Php,Mysql,Doctrine,Symfony 1.4,Left Join,我试图通过检查两个关联表中的变量来获取一个表的单个记录 例如,我的桌子是 user: id | name 3781 | Foo Manchu user_programs: id | user_id | page_id 4150 | 3781 | 16974 Page id | title | section_id 16974 | Dudes | 3 所以我需要查询并返回section_id为3的用户 用户与用户程序表相关联,用户程序
user:
id | name
3781 | Foo Manchu
user_programs:
id | user_id | page_id
4150 | 3781 | 16974
Page
id | title | section_id
16974 | Dudes | 3
所以我需要查询并返回section_id为3的用户
用户与用户程序表相关联,用户程序表通过页面id与特定页面相关联
这就是我所拥有的东西,它不会归还任何东西:
if($section_id == 3) {
$q = $this->createQuery('u');
$q->leftJoin('u.user_programs up');
$q->leftJoin('up.Page p');
$q->where('u.published=1 AND u.is_preview = 0 AND u.featured=1 AND fp.deleted_at IS NULL');
$q->addWhere('p.section_id=?', $section_id);
$q->orderBy('RAND()')->limit(1);
我可以在不进行联接的情况下成功返回u查询,但我需要将查询限制为仅返回关联页面(共3页)上具有节id的用户。如果架构正确,则用户应该具有页面(或类似的)关系。您可以这样编写查询:
$query = $this->createQuery('u')
->innerJoin('u.Pages p')
->andWhere('u.published = ?', 1)
->andWhere('u.is_preview = ?', 0)
->andWhere('u.featured = ?', 1)
->addWhere('p.section_id = ?', $section_id)
->limit(1)
;
我删除了部分的fp.deleted\u,因为在使用SoftDelete
时它没有任何意义(我想您会使用它),并且fp
别名无论如何都不在原始查询中