我想绑定模型,主要是因为数据源从一个模型变为另一个模型。我们说我有以下问题:
SELECT ext.col1, ext.col2, ext.col3, COUNT(*) Link Count
FROM `external.`Media` ext
INNER JOIN `internal`.`links` l ON ext.someId = links.id
INNER JOIN `internal`.tags t ON l.tag_id = t.tag_id
WHERE t.parent_tag_id = 1098
AND t.metadata = 'someValue'
GROUP BY ext.col1, ext.col2, ext.col3
所以我有3个数据来自哪个模型。目前我在Media
模型中有以下内容..
public $belongsTo = array(
'Links' => array(
'className' => 'Links',
'foreignKey' => 'someId',
),
'Tag' => array(
'className' => 'Tag'
)
);
然后在其他模型中:
标记模型
public $useTable = "tags";
public $name = 'Tag';
public $hasAndBelongsToMany = array(
'TagLink' => array(
'className' => 'TagLink',
'foreign_key' => 'tag_id',
'conditions' => array(
'Tag.parent_tag_id' => 1098
)
)
);
链接模型
public $useTable = "tag_links";
public $name = 'TagLink';
public $hasAndBelongsToMany = array(
'Tag' => array(
'className' => 'Tag',
'foreign_key' => 'tag_id'
)
);
然后回到Media
模型,我使用期望设置模型绑定的find:
return $this->find("all", array(
'conditions' => array(
'Tag.metadata' => $username
)
));
这会产生错误:
Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Tag.metadata' in 'where clause'
我假设发生了这种情况,因为找不到表格
[SQL Generated]
SELECT `Media`.`media_id`, `Media`.`mediatype`, `Media`.`created`, `Media`.`active_flag`,
`Media`.`mediafile`, `Media`.`fallbackfile`, `Media`.`setupId`, `Media`.`externalId`,
`Media`.`width`, `Media`.`height`, `Media`.`brands`, `Media`.`languages`, `Media`.`products`,
`Media`.`projects`, `Media`.`affiliates`, `Media`.`description`, `Media`.`linking_code` FROM
`external`.`ext_media_gallery` AS `Media` WHERE `Tag`.`metadata` = 'testuser' AND
`MediaGallery`.`active_flag` = 'active' AND ((FIND_IN_SET('testuser', `Media`.`affiliates`)) OR
(`Media`.`affiliates` = ''))
这基本上表明绑定不正确/没有发生
基本上我想替换以下内容以避免动态使用连接,因为这些需要应用于每个查询..因此模型绑定..
这适用于我,但我想将其转换为使用模型绑定来执行此操作:
return $this->find("all", array(
"joins" => array(
array(
"table" => "internal.links",
"alias" => "Link",
"type" => "INNER",
"conditions" => array(
"Link.id = Media.someId"
)
),
array(
"table" => "internal.tags",
"alias" => "Tag",
"type" => "INNER",
"conditions" => array(
"Tag.tag_id = Link.tag_id",
"Tag.parent_tag_id = 3214",
"Tag.metadata" => $username
)
),
)
));