【问题标题】:Kohana orm - get child and grand-child objectKohana orm - 获取子对象和孙对象
【发布时间】:2013-08-26 21:11:36
【问题描述】:

我在 Kohana ORM 中加载对象子项时遇到问题。
我的数据库表看起来是这样的:

-objects (something like "houses", but objects sounds better in my opinion)
  -id
  -name
  -title
  -author
  -city (id link to cities.city_id)
  -description
  -access
-cities
  -city_id
  -country (id link to countries.country_name)
  -city_name
-countries
  -country_id
  -country_name

和我的模型:

class Model_Object extends ORM
{
    protected $_table_name = 'objects';
    protected $_table_columns = array(
        'id' => NULL,'name' => NULL,
        'title' => NULL,
        'author' => NULL,
        'city' => NULL,
        'description' => NULL,
        'access' => NULL,
        'created' => NULL
    );
    protected $_primary_key = 'id';
    protected $_has_one = array(
        'city'=>array(),
        'author'=>array(
            'model'=>'User',
            'foreign_key'=>'user_id',
        )
    );
}

class Model_City extends ORM
{
    protected $_table_name = 'cities';
    protected $_table_columns = array('city_id'=>NULL,'city_name'=>NULL);
    protected $_primary_key = 'city_id';
    protected $_has_one = array('country'=>array(
        'model'=>'country',
        'foreign_key'=>'country',
    ));
    protected $_belongs_to = array(
        'objects'=>array(),
    );
}

class Model_Country extends ORM
{
    protected $_table_name = 'countries';
    protected $_table_columns = array(
        'country_id'=>NULL,
        'country_name'=>NULL,
    );
    protected $_primary_key = 'country_id';
    protected $_belongs_to = array(
        'cities'=>array(
            'model'       => 'city',
            'foreign_key' => 'country'
        ),
    );
}

我需要获取对象的对象,包括国家和城市的名称。我发现了这个:

ORM::factory('Object')->with('City')->with('City:Country')->find_all();

here 但它返回城市 ID 而不是城市对象。
所以我的问题是:如何在我呈现的表格中使用子对象获取对象的对象?

【问题讨论】:

    标签: php orm kohana


    【解决方案1】:

    您可以通过这种方式查看正在执行的查询:

    echo View::factory('profiler/stats');
    

    我认为主要问题是你的关系。带有城市和城市:国家的 find_all 对象看起来不错。

    您可能需要考虑遵循 Kohana ORM 命名约定。所以表将是对象、城市和国家,它们都将 id 作为主键。对象表将有一个 city_id 列(引用城市表中的 id),城市将有 country_id 将“指向”国家表中的 id 列。如果您保持表、列和模型的名称正确,您甚至不需要在模型中单独定义表名或外键。

    现在,由于每个对象都有一个分配给它的城市,并且每个城市可能有零到 n 个对象,您想在对象模型中声明它属于城市。在城市模型中使用 HAS MANY 对象。

    还有城市属于国家和国家有很多城市。

    现在你应该可以得到如下数据了:

    $objects = ORM::factory('Object')->with('City')->with('City:Country')->find_all();
    
    $objects = $cityObject->objects->find_all();
    
    $cities = $countryObject->cities->find_all();
    

    等等

    有关关系的更多信息可以找到here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-13
      • 2011-09-29
      • 1970-01-01
      • 1970-01-01
      • 2012-09-16
      • 1970-01-01
      • 1970-01-01
      • 2019-05-31
      相关资源
      最近更新 更多