Zend Query中有很多很多连接,希望只是略微调整一下

时间:2010-02-25 23:08:40

标签: php zend-framework zend-db zend-db-select

为所有这些代码道歉,无论如何我正在重新查询Zend查询工作方式,这是我到目前为止所做的:

$db = Zend_Registry::get ( "db" );      
    $stmt = $db->query('
    SELECT recipe_pictures.picture_id, recipe_pictures.picture_filename, course.course_name, cuisines.name, recipes.id, recipes.Title, recipes.Method, recipes.author, recipes.SmallDesc, recipes.user_id, recipes.cuisine, recipes.course, recipes.Created_at, recipes.vegetarian, recipes.Acknowledgements, recipes.Time, recipes.Amount, recipes.view_count, recipes.recent_ips, guardian_writers.G_item, guardian_writers.G_type
    FROM recipes
    LEFT JOIN course ON recipes.course = course.course_id
    LEFT JOIN recipe_pictures ON recipes.id = recipe_pictures.recipe_id
    LEFT JOIN cuisines ON recipes.cuisine = cuisines.id
    LEFT JOIN guardian_writers ON recipes.author = guardian_writers.G_author
    WHERE recipes.id = ?', $id);
    $stmt->setFetchMode(Zend_Db::FETCH_ASSOC);
    $recipes = $stmt->fetchAll();

    return $recipes;

上面的那个工作,试图正确地获得Zend版本,我的努力在下面。

    $db = Zend_Registry::get ( "db" );      
    $select = $db->select()
                 ->from(array('r' => 'recipes'))
                 ->join(array('c' => 'course'),
                        'r.course = c.course_id')
                 ->join(array('rp' => 'recipe_pictures'),
                        'r.id = rp.recipe_id')
                 ->join(array('cui' => 'cuisines'),
                        'r.cuisine = cui.id')
                 ->join(array('gw' => 'guardian_writers'),
                        'r.author = gw.G_author')
                 ->where(' id = ? ', $id);

    $recipes = $db->fetchRow($select);

    return $recipes;

如果有人能发现错误,我将非常感激,谢谢

2 个答案:

答案 0 :(得分:2)

使用joinLeft而不是join来生成左连接。

要从表中获取特定列,而不是全部(*)使用此:

->from(array('r' => 'recipes'), array('id', 'title', 'method'))

->joinLeft(array('rp' => 'recipe_pictures'),
                    'r.id = rp.recipe_id',
                    array('picture_id', 'picture_filename')
                    )

要从表中不提取任何列,请将空数组作为第三个参数传递。

答案 1 :(得分:0)

join方法提供了一个sql INNER JOIN。如果您想获得LEFT JOIN,请使用joinLeft