【问题标题】:Can FuelPHP ORM handle this database design?FuelPHP ORM 可以处理这种数据库设计吗?
【发布时间】:2012-01-29 15:34:22
【问题描述】:

我想知道 Fuel ORM 是否可以处理此处描述的设计:

http://www.codeproject.com/KB/aspnet/LocalizedSamplePart2/normalizedSchema.gif

必须生成并执行以下 SQL 或类似的 SQL:

SELECT CultureId
FROM Culture WHERE CultureName = @CultureName

SELECT I.ItemId, IL.[Name], IL.[Description],
I.Price, CL.[Name], CL.[Description]
FROM Item I
INNER JOIN Item_Locale IL ON I.ItemId = IL.ItemID AND IL.CultureId = @CultureIdD
INNER JOIN Category C ON I.CategoryId = C.CategoryId
INNER JOIN Category_Locale CL ON C.CategoryID = CL.CategoryId AND CL.CultureId = @cultureId
WHERE I.SellerId = @SellerID

或者我必须使用普通查询?

请指教。

【问题讨论】:

标签: php orm fuelphp


【解决方案1】:

您需要按照in the link already given 的说明配置主键和外键。

从给定关系的示例来看:

  • Item HasOne Item_Locale
  • Item_Locale 属于项目
  • 项目有很多类别
  • 类别属于项目
  • 类别有一个 Category_Locale
  • Category_Locale 属于类别

查询看起来像这样:

$items = Model_Item::query()
    ->related('locale')
    ->related('categories')
    ->related('categories.locale')
    ->where('SellerID', $sellerID)
    ->get();

我假设语言环境在运行时不会改变,但不能硬编码。在这种情况下,您需要以下内容。首先设置默认条件,这些条件始终是关系的一部分。这些需要添加到模型中的关系定义中,例如 Model_Item 中的以下示例。

protected static $_has_one = array(
    'locale' => array(
        'model_to' => 'Model_Item_Locale',
        'key_from' => 'ItemId',
        'key_to' => 'ItemId',
        'conditions' => array(
            'join_type' => 'inner',
            'where' => array(),
        ),
    ),
);

我还不能添加实际的 where 条件,因为它必须是动态的,你不能在类属性定义中使用它。因此,我们将在加载类的毫秒数添加它:

public static function _init()
{
    $culture_id = ; // get that from somewhere
    static::$_has_one['locale']['where'][] = array('CultureId', '=', $culture_id);
}

这将被添加到每次加入部分,在主键-外键匹配旁边。

查询将返回一组项目,这些项目将在属性中包含语言环境信息,并具有一个类别数组,这些类别都有自己的语言环境属性来描述它们。

foreach ($items as $i)
{
    echo $i->locale->Name;
    foreach ($i->categories as $c)
    {
        echo $c->locale->Name;
    }
}

【讨论】:

  • 这里只是一个简短的说明 - $culture_id 必须 是一个字符串,否则 ORM 出于某种原因将其封装在反引号而不是引号中。 (string) $culture_id 解决了这个问题。
猜你喜欢
  • 2010-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-27
相关资源
最近更新 更多