Kohana ORM - Incorrect table name

一笑奈何 提交于 2020-01-06 08:23:08

问题


I have a weird problem with the Kohana (3.2) ORM query builder and i can't figure out what is wrong. I get "Incorrect table name" exception:

  Database_Exception [ 1103 ]: Incorrect table name '' [ SELECT ``.* FROM `` JOIN `user_plugins` ON (`user_plugins`.`plugin_id` = ``.`id`) WHERE `user_plugins`.`user_id` = '9' ]

As you can see the table is empty in the query.

Controller:

  $user = ORM::factory('user', Auth::instance()->get_user()->id);

  if ($user->loaded() ) 
  {
     $result = $user->plugin->find_all();
  }

User model:

  class Model_User extends Useradmin_Model_User
  {
    protected $_has_many = array(
      'plugin' => array( 'through' => 'user_plugins'),
    );
  ...

user_plugin Model

  class Model_user_plugin extends ORM
  {
     protected $_belongs_to = array(
         'plugin' => array(),
         'user' => array()
     );
  ...

plugin Model

  class Model_Plugin extends ORM
  {
     protected $_has_many = array(
         'user' => array('through' => 'user_plugins')
     );
  ...

Anyone got any idea what could be wrong here? Any help is very appreciated!


回答1:


This is how User Model should be

class Model_User extends Useradmin_Model_User
{
   protected $_has_many = array(
      'plugin' => array('model' => 'plugin', 'through' => 'user_plugins'),
   );
...

This is how Plugin Model should be

class Model_Plugin extends ORM
{
    protected $_has_many = array(
        'user' => array('model' => 'user', 'through' => 'user_plugins')
    );

You don't need user_plugin Model at all, the "user_plugins" in both models refers to the table name, not the model name. Just make sure you have the table with user_plugins that have following fields,

id, user_id, plugin_id

I hope this helps.




回答2:


The $_has_many, by convention, must always use plural names, unless you specify the name in $_object_name in the target model. So it should be:

class Model_Plugin extends ORM
{
  protected $_has_many = array(
     'users' => array('through' => 'users_plugins')
  );
  //...
class Model_User extends ORM
{
  protected $_has_many = array(
     'plugins' => array('through' => 'users_plugins')
  );
  //...
class Model_user_plugin extends ORM
{
  protected $_belongs_to = array(
     'plugin' => array(),
     'user' => array()
  );
  //...


来源:https://stackoverflow.com/questions/13627891/kohana-orm-incorrect-table-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!