【问题标题】:FuelPHP - How do I access a custom sql statement using ORM?FuelPHP - 如何使用 ORM 访问自定义 sql 语句?
【发布时间】:2013-10-23 20:09:04
【问题描述】:

问题

是否可以创建自定义 SQL 查询并像使用 FuelPHPs ORM 处理表一样处理其结果?


示例

我有一个 SQL 语句可以为我旋转一个表。下图显示了枢轴 SQL 语句的作用。左侧是“属性”表,右侧是 SQL 透视语句的结果。

SQL Pivot 语句结果:

SQL Pivot 语句:

SELECT
  item_id,
  MAX(IF(property_name = 'color', value, NULL)) AS color,
  MAX(IF(property_name = 'size', value, NULL)) AS size,
  ...
  ...
  ...
FROM
  properties
GROUP BY
  item_id;

问题:

我可以执行上面的语句,然后通过普通的ORM方法例如访问列

echo $table->color;
$table->color = 'blue';
$table->save();

另外,我查看了FuelPHP EAV,看起来它可能是我需要的......但我无法让它工作。这是我需要的吗?

我从a buysql.com tutorial on pivot tables 得到了上面的代码。它完全符合我的需要,但不确定如何与 ORM 集成。

【问题讨论】:

    标签: orm fuelphp fuelphp-orm


    【解决方案1】:

    我得到了一些“有用”的东西,如果有更好的方法,请告诉我。

    1) 让sql创建一个临时表。

    CREATE TEMPORARY TABLE IF NOT EXISTS temp_compiled_properties AS
    (SELECT
      item_id,
      MAX(IF(property_name = 'color', value, NULL)) AS color,
      MAX(IF(property_name = 'size', value, NULL)) AS size,
      ...
      ...
      ...
    FROM
      properties
    GROUP BY
      item_id);
    

    2) 创建模型

    //this is not a typical ORM model and cannot be accessed as such
    //You must first run the init function before data can be accesses
    //You can read data from the model, other methods may work, but not all ORM functions have been tested with this model.
    
    class Model_Properties_Pivot extends \Orm\Model
    {
        //--------------------------------------
        //Table Details
        //--------------------------------------
        protected static $_table_name = 'temp_compiled_properties';
        protected static $_primary_key = array('item_id');
    
        //dont define properties, ORM will automatically query the temp table to get these
        //protected static $_properties = array();
    
        public static function init($game_id)
        {   
            $sql = "CREATE TEMPORARY TABLE IF NOT EXISTS temp_compiled_properties AS
                (SELECT
                   item_id,
                   MAX(IF(property_name = 'color', value, NULL)) AS color,
                   MAX(IF(property_name = 'size', value, NULL)) AS size,
                   ...
                   ...
                   ...
                FROM
                   properties
                GROUP BY
                   item_id)";
    
            DB::query($sql)->execute();
        }
    

    3) 读取模型中的数据

    Model_Properties_Pivot::init(14);
    $all_data = Model_Properties_Pivot::query()->get();
    

    另外,我研究了 EAV 并让它工作。问题是我的“属性”字段实际上是另一个外键(自动增量编号)。这意味着我无法使用它,因为它是一个自动增量编号。基本上不能这样访问$properties->10

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多