【问题标题】:CakePHP filter list by slug instead of IDCakePHP 通过 slug 而不是 ID 过滤列表
【发布时间】:2011-11-30 02:33:36
【问题描述】:

我正在使用 CakePHP,这是我的数据库的结构:

汽车制造商 ---------------------------------- ID 弹头名称 16 福特 福特 车型 ---------------------------------- ID 名称 CarMake_ID 10 护送 16 汽车 ---------------------------------- ID 名称 CarModel_ID 1 我的车 10

我想查看 CarMakes.Slug 的汽车列表

所以网址是: http://localhost/cars/ford

任何想法或信息的一般方向?

【问题讨论】:

    标签: php database url cakephp slug


    【解决方案1】:

    您可以使用 findBy()findAllBy() 来检索基于 ID 以外的其他内容的记录。如果您需要为查询提供条件,请使用常规find()

    $this->Car->find(
       'all',
       array(
          'conditions' => array(
             'CarMake.Slug' => $slug,
             'Car.Name LIKE' => $name
          ),
       )
    );
    

    另外,对于您尝试设置的 URL,您需要为 /cars 创建一个 route

    Router::connect(
       '/cars/:make',
       array('controller' => 'cars', 'action' => 'bymake'),
       array(
          'pass' => array('make'),
          'make' => '[A-Za-z]+'
       )
    );
    

    编辑:

    如果您的条件基于与您的模型的直接关联,则上述方法有效。如果您的条件是递归关联(即 Car->CarModel->CarMake),则需要使用显式连接:

    $result = $this->Car->find('all', array(
        'joins' => array(
            array(
                'table' => 'car_models',
                'type' => 'inner',
                'foreignKey' => false,
                'conditions' => array('car_models.id = Car.car_model_id')
            ),
            array(
                'table' => 'car_makes',
                'type' => 'inner',
                'foreignKey' => false,
                'conditions' => array(
                    'car_makes.id = car_models.car_make_id',
                    'car_makes.slug' => $slug
                )
            )
        ),
        'conditions' => array(
            'Car.name LIKE' => $name
        )
    ));
    

    【讨论】:

    • 非常感谢您为我写这篇文章的努力,我会试一试的。
    • 我昨晚试了一下,我看到它现在在做什么,但我收到了这个 SQL 错误:`SQL 错误:1054:'where 子句'中的未知列'CarMake.Slug'[ CORE/cake/libs/model/datasources/dbo_source.php,第 684 行]
    • 您的模型中是否定义了 Car 和 CarMake 之间的关联?
    • 不仅是 Car 和 CarModel,它们之间并没有真正的直接关系:` var $belongsTo = array( 'Carmodel' => array( 'className' => 'Carmodel', 'foreignKey ' => 'carmodel_id', 'conditions' => '', 'fields' => '', 'order' => '' ) );
    • 查看解决递归关系条件的更新答案。
    猜你喜欢
    • 2014-11-17
    • 2016-02-29
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    • 2020-03-07
    • 1970-01-01
    • 2015-11-18
    • 2013-01-08
    相关资源
    最近更新 更多