使用Model建立表间内连接
Using Model to establish inner join between tables
我正在尝试建立两个表 articles 和 categories 之间的关系。这是一对一的关系,其中 articles.category_id = categories.id
。我有以下设置。
controllers/home.cfc
<cfcomponent extends="Controller">
<cffunction name="index">
<cfset qFeaturedArticles = model("articles").findAll(
where="show_homepage = 1",
include="categories",
order="homepage_order"
) />
</cffunction>
</cfcomponent>
model/categories.cfc
<cfcomponent extends="Model">
<cffunction name="init">
<cfset hasOne("articles", foreignKey="category_id") />
</cffunction>
</cfcomponent>
model/articles.cfc
<cfcomponent extends="Model">
<cffunction name="init">
<cfset belongsTo("categories", dependent="nullify") />
</cffunction>
</cfcomponent>
这是我遇到的错误。
在第 4 行第 49.ColdFusion 列发现无效的 CFML 构造正在查看以下文本:=
CFML 编译器正在处理:
- 第 4 行第 16.This 列消息以 belongsTo 开头的表达式通常是由表达式结构中的问题引起的。
- A cfset 标记开头在第 4 行第 10 列。
- 从第 4 行第 10 列开始的 cfset 标记。
包含或处理的文件的特定顺序是:\cfusion\wwwroot\foo\index.cfm,行:4
首先我想指出categories.cfc模型。如果您指定 hasOne
关系,那么在这种情况下,代码应如下所示:
<cfset hasOne("article", foreignKey="category_id") />
请注意,在 hasOne
的情况下,您需要输入 article
而不是 articles
。
但是,从字面上看,类别和文章之间的关系应该是one to many
。我的意思是一个类别可以有很多文章。
所以categories.cfc应该这样写:
<cfcomponent extends="Model">
<cffunction name="init">
<cfset hasMany("articles", foreignKey="category_id") />
</cffunction>
我正在尝试建立两个表 articles 和 categories 之间的关系。这是一对一的关系,其中 articles.category_id = categories.id
。我有以下设置。
controllers/home.cfc
<cfcomponent extends="Controller">
<cffunction name="index">
<cfset qFeaturedArticles = model("articles").findAll(
where="show_homepage = 1",
include="categories",
order="homepage_order"
) />
</cffunction>
</cfcomponent>
model/categories.cfc
<cfcomponent extends="Model">
<cffunction name="init">
<cfset hasOne("articles", foreignKey="category_id") />
</cffunction>
</cfcomponent>
model/articles.cfc
<cfcomponent extends="Model">
<cffunction name="init">
<cfset belongsTo("categories", dependent="nullify") />
</cffunction>
</cfcomponent>
这是我遇到的错误。
在第 4 行第 49.ColdFusion 列发现无效的 CFML 构造正在查看以下文本: = CFML 编译器正在处理:
包含或处理的文件的特定顺序是:\cfusion\wwwroot\foo\index.cfm,行:4
首先我想指出categories.cfc模型。如果您指定 hasOne
关系,那么在这种情况下,代码应如下所示:
<cfset hasOne("article", foreignKey="category_id") />
请注意,在 hasOne
的情况下,您需要输入 article
而不是 articles
。
但是,从字面上看,类别和文章之间的关系应该是one to many
。我的意思是一个类别可以有很多文章。
所以categories.cfc应该这样写:
<cfcomponent extends="Model">
<cffunction name="init">
<cfset hasMany("articles", foreignKey="category_id") />
</cffunction>