php - CakePHP 通过 slug 而不是 ID 过滤列表

标签 php database url cakephp slug

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

CarMakes
----------------------------------
ID     Slug     Name
16     ford     Ford

CarModels
----------------------------------
ID     Name     CarMake_ID
10     Escort   16

Cars
----------------------------------
ID     Name     CarModel_ID
1      My car   10

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

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

有什么想法或一般信息方向吗?

最佳答案

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

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

此外,对于您尝试设置的 URL,您需要创建 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
    )
));

关于php - CakePHP 通过 slug 而不是 ID 过滤列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7638433/

相关文章:

php - 单独拉出 PHP 日期和时间

php - 根据搜索查询从数据库返回行

java - 将时间戳从数据库转换为 java.sql.Timestamp

spring - 带有多个参数的href spring

java - 如何检测字符串中是否存在 URL

php - 计算 mySQL 中的值

php - 每笔交易使用不同的 PayPal IPN URL

sql - INSERT INTO SELECT 非常慢,但 INSERT 或 SELECT 单独运行时速度很快

ftp 服务器上的 Java Applet 需要几分钟才能连接到 MySQL 数据库

regex - 没有 http ://www 的 url 正则表达式