php - “通过”与 CakePHP 3 中的 'foreign_key' 和 'model' 字段的关联

标签 php mysql cakephp associations cakephp-3.0

这是一个非常标准的事情,我在 CakePHP 2 中大概做了 600 次,但就我的生活而言,我无法让它在 CakePHP 3 中工作。

我有视频照片文章。我还有 类别

视频、照片和文章都可以属于一个或多个类别。

当前问题的目标是拉取某个类别下的视频。

所以,我尝试了这个:

// VideosTable
$this->belongsToMany('Categories', [
    'joinTable' => 'categorized',
    'className' => 'Categorized',
    'foreignKey' => 'foreign_key',
    'conditions' => [
        'Categorized.model' => 'Videos',
    ]
]);

public function getTopVideosByCategory($categorySlug)
{
    return $this->Categories->find('all')
        ->where(['Categories.slug' => $categorySlug])
        ->contain([
            'Videos' => function ($q) {
                return $q
                    ->limit(8)
                    ->contain([
                        'Tags',
                        'Categories' // tried with and without this
                    ])
                    ->order([
                        'Videos.featured' => 'DESC',
                        'Videos.created' => 'DESC'
                    ]);
            }
        ])
        ->first();
}

Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Categorized.model' in 'where clause'

我已经尝试了许多其他方法,包括创建连接表的模型,以及其他一些方法,但总是出现错误。我已经尝试了每个选项,并且选项数量有限。我尝试过使用实际的 Table 类,也尝试过伪类(如上面的“分类”)。

我不得不假设这是非常标准的,但在书中找不到示例,而且我似乎无法让它工作。


编辑:

我也试过这个:

//VideosTable
public function initialize(array $config)
{
    $this->belongsToMany('Categories', [
        'through' => 'Categorized',
        'conditions' => [
            'Categorized.model' => $this->alias(),
        ]
    ]);
}

public function getTopVideosByCategory($categorySlug)
{
    return $this->find('all')
        ->matching('Categories', function ($q) use ($categorySlug) {
            return $q
                ->where(['Categories.slug' => $categorySlug]);
        })
        ->contain([
            'Tags',
            'Categories'
        ])
        ->limit(8)
        ->order([
            'Videos.featured' => 'DESC',
            'Videos.created' => 'DESC'
            ])
        ->first();
}

但是得到这个错误:

Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Categorized.model' in 'on clause'

最佳答案

由于 Videos and Categories 不是 1-1 o n-1(hasOne 或 belongsTo),因此不可能构建可以包含其他表条件的 SQL 表达式。对于这些情况,CakePHP 实现了 matching() 函数。它的工作方式与 contain() 类似,但它的作用是使用 INNER 连接从外部关联获取数据:

http://book.cakephp.org/3.0/en/orm/retrieving-data-and-resultsets.html#filtering-by-associated-data

您还可以在此处查看使用它的示例:

http://book.cakephp.org/3.0/en/tutorials-and-examples/bookmarks/intro.html#creating-the-finder-method

关于php - “通过”与 CakePHP 3 中的 'foreign_key' 和 'model' 字段的关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29643151/

相关文章:

用于嵌套数组的 PHP 唯一数组函数

mysql - 如何正确执行使用这些表中的 2 个不同字段 JOIN 2 个表的查询?

mysql - 我无法弄清楚这个查询

javascript - $http获取返回html源代码angularjs

php - PHP 正则表达式模式中需要额外的反斜杠

PHPExcel 无法工作

php - 告诉 Ctags 不要解析评论中的内容

php - 在 laravel 中使用或声明

mysql - 在聚合子查询或连接中计数

cakephp - $html->cakephp 中的链接中的警报框